Search code examples
goruntimeexecutiongoroutine

Why does the execution time of Goroutines differ significantly?


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?


Solution

  • 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.