| 1 | package main |
| 2 | |
| 3 | import "fmt" |
| 4 | import "log" |
| 5 | import "os" |
| 6 | import "time" |
| 7 | import "strconv" |
| 8 | |
| 9 | func assert_eq(a, b int64) { |
| 10 | if a != b { |
| 11 | log.Fatalf("assertion failed\nleft: %d, right: %d\n", a, b) |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | func 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 | |
| 25 | func do_send(ch chan int32, start, end int32) { |
| 26 | for i := start; i < end; i++ { |
| 27 | ch <- i |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func 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 | |