/
goroutine.go
83 lines (70 loc) · 1.42 KB
/
goroutine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"runtime"
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"testing"
)
func main() {
runtime.GOMAXPROCS(2)
bmResult := testing.Benchmark(Benchmark_sleeper)
fmt.Println("sleep(3)", bmResult)
bmResult = testing.Benchmark(Benchmark_go_sleeper)
fmt.Println("5 go func", bmResult)
bmResult = testing.Benchmark(Benchmark_fib)
fmt.Println("fib(32)", bmResult)
bmResult = testing.Benchmark(Benchmark_go_fib)
fmt.Println("5 go fib(32)", bmResult)
}
func Benchmark_sleeper(b *testing.B) {
db, e := sql.Open("mysql", "root@tcp(localhost:3306)/")
if e != nil {
panic(e.Error())
}
defer db.Close()
db.Exec("SELECT sleep(3)")
}
func Benchmark_go_sleeper(b *testing.B) {
db, e := sql.Open("mysql", "root@tcp(localhost:3306)/")
if e != nil {
panic(e.Error())
}
defer db.Close()
ch := make(chan sql.Result, 5)
for i := 0; i < 5; i++ {
go func() {
result, e := db.Exec("SELECT sleep(3)")
if e != nil {
panic(e.Error())
}
ch <- result
}()
}
for i := 0; i < 5; i++ {
<-ch
}
}
func fib(n int) int {
var r int
if n < 2 {
r = n
} else {
r = fib(n - 1) + fib(n - 2)
}
return r
}
func Benchmark_fib(b *testing.B) {
fib(32)
}
func Benchmark_go_fib(b *testing.B) {
ch := make(chan int, 5)
for i := 0; i < 5; i++ {
go func() {
ch <- fib(32)
}()
}
for i := 0; i < 5; i++ {
<-ch
}
}