dpfwhb7470 2019-03-10 11:17
浏览 104
已采纳

为什么Goroutines的执行时间会明显不同?

I'm just measuring the execution time of a set of goroutines. That means:

I start measuring, then start 20 goroutines and stop measuring as soon as they finish. I repeat that process like 4 times and then compare the 4 exection times.

Sometimes, these execution times differ significantly:

1st run of the 20 goroutines: 1.2 ms
2nd run of the 20 goroutines: 1.9 ms
3rd run of the 20 goroutines: 1.4 ms
4th run of the 20 goroutines: 17.0 ms!

Why does it sometimes differ so significantly? Is there any way to avoid it?

  • 写回答

1条回答 默认 最新

  • duanjie1339 2019-03-10 11:41
    关注

    Why does it sometimes differ so significantly?

    Execution time will always be unpredictable to some point, as mentioned in comments to your questions (CPU, disk load, memory, etc.)

    Is there any way to avoid it?

    There is a way to make your measurements more useful. Go has a built-in benchmark tool (here is a guide on how to use it properly). This tool runs your code just enough times to determine a somewhat deterministic execution time.

    In addition to showing average execution time for your code, it can also show useful memory information.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?