duanjing9339 2016-02-05 19:20
浏览 26

基准Go代码和goroutines

I would like to benchmark a function: test(), with different numbers of threads working on it.

Without goroutines:

var t1 = time.Now()
test()
var elapsed1 = time.Since(t1)

1 ns / operation

With goroutines:

runtime.GOMAXPROCS(1)
var t1 = time.Now()
go test()
var elapsed1 = time.Since(t1)

1.10^-6 ns / operation

My test function:

func test() {
    for i := 0; i < 1000000000; i++ {
        float_result = f1 + f2
        float_result = f1 - f2
        float_result = f1 * f2
        float_result = f1 / f2
        float_result = f1 + f2
        float_result = f1 - f2
        float_result = f1 * f2
        float_result = f1 / f2
        float_result = f1 + f2
        float_result = f1 - f2
        float_result = f1 * f2
        float_result = f1 / f2
        float_result = f1 + f2
        float_result = f1 - f2
        float_result = f1 * f2
        float_result = f1 / f2
        float_result = f1 + f2
        float_result = f1 - f2
        float_result = f1 * f2
        float_result = f1 / f2
    }
}
  • Is the test() function well benchmarked when I use goroutines in this case?
  • How is it possible to reach 0.001ns / operation? It looks to be way too fast. (2.5GHz Intel Core i7)
  • Is the use of goroutines with runtime.GOMAXPROCS(n) equivalent to use n threads ?
  • 写回答

2条回答 默认 最新

  • dtry54612 2016-02-05 19:27
    关注

    You are tring to benchmark something so small that measurement error dominates. Your benchmark iterations should be adjusted until the benchmark function lasts long enough to be timed reliably.Your benchmark should run for about one second to be meaningful.

    评论

报告相同问题?