v2 / vlib / sync / bench / channel_bench_go.go
68 lines · 63 sloc · 1.49 KB · d63daa0798fcff1722f7c4d930557f1304934069
Raw
1package main
2
3import "fmt"
4import "log"
5import "os"
6import "time"
7import "strconv"
8
9func assert_eq(a, b int64) {
10 if a != b {
11 log.Fatalf("assertion failed\nleft: %d, right: %d\n", a, b)
12 }
13}
14
15func do_rec(ch chan int32, resch chan int64, n int32) {
16 var sum int64
17 var i int32
18 for i = 0; i < n; i++ {
19 sum += int64(<- ch)
20 }
21 fmt.Println(sum)
22 resch <- sum
23}
24
25func do_send(ch chan int32, start, end int32) {
26 for i := start; i < end; i++ {
27 ch <- i
28 }
29}
30
31func main() {
32 if len(os.Args) != 5 {
33 log.Fatalf("usage:\n\t%s <nsend> <nrec> <buflen> <nobj>\n", os.Args[0])
34 }
35 nsend, _ := strconv.Atoi(os.Args[1])
36 nrec, _ := strconv.Atoi(os.Args[2])
37 buflen, _ := strconv.Atoi(os.Args[3])
38 nobj, _ := strconv.Atoi(os.Args[4])
39 stopwatch := time.Now()
40 ch := make(chan int32, buflen)
41 resch := make(chan int64, 0)
42 no := nobj
43 for i := 0; i < nrec; i++ {
44 n := no / (nrec - i)
45 go do_rec(ch, resch, int32(n))
46 no -= n
47 }
48 assert_eq(int64(no), 0)
49 no = nobj
50 for i := 0; i < nsend; i++ {
51 n := no / (nsend - i)
52 end := no
53 no -= n
54 go do_send(ch, int32(no), int32(end))
55 }
56 assert_eq(int64(no), 0)
57 var sum int64
58 for i := 0; i < nrec; i++ {
59 sum += <-resch
60 }
61 elapsed := time.Now().Sub(stopwatch)
62 rate := float64(nobj)/float64(elapsed.Nanoseconds())*1000.0
63 duration := 1.0e-09 * float64(elapsed.Nanoseconds())
64 fmt.Printf("%d objects in %g s (%.2f objs/µs)\n", nobj, duration, rate)
65 expected_sum := int64(nobj)*int64(nobj-1)/2
66 fmt.Printf("got: %d, expected: %d\n", sum, expected_sum)
67 assert_eq(sum, expected_sum)
68}
69