Why does using time.time() to measure the execution time return different results each time?

Viewed 39

I'm trying to measure the time a function I made uses like this:

start = time.time()
function("does_something")
end = time.time()
function_time = end - start 

However, every time I run this I get a (slightly) different solution. What is the reason for this? I know I can do a Monte Carlo Simulation to make this measurement somewhat more reliable but I am curious to know what the reason for this difference in results is.

1 Answers

Even though the CPU in your computer likely contains multiple cores, the scheduler in your operating system distributes small time slots to all the programs that want to run over the different CPU cores. How much time your program gets depends on how much processes are asking for processor time and their relative priority.

Since time.time() returns the time since the epoch ("wall time"), it will be influenced by scheduling et cetera.

You could try using time.process_time() instead. This only counts system and user CPU time for your process, so it should have less variation.

CPU time is not the only bottleneck, though. Both disk I/O and network I/O are orders of magnitude slower than the CPU. It is pretty easy for a single program like e.g. netcat to saturate a 100 Mbit/s network link.

So if your program tries to do network I/O it will make a difference if you are e.g. streaming video or downloading software at the same time.

Related