The way to accurately measure Python execution time

2014-02-19
2019-01-06

What is the best way to measure the time that it takes to run a Python program?

The easiest way, which is often introduced by many websites, is to use time.time() or time.perf_counter() and subtract the start time from the end time. But I wonder if measured time is accuracy.

The methods of the time library

These methods are added to the time library in Python version 3.3.

time.perf_counter()

  • Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. (by the official documentation)
  • Can measure the time during PC sleeping

time.process_time()

  • Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. (by the official documentation)
  • Cannot measure the time during PC sleeping

These methods return the value in the float type. If you want to get the value in the int type, you can use below methods (in version 3.7):

  • time.perf_counter_ns()
  • time.process_time_ns()

These return the time in nanoseconds but perf_counter() is more accurate than process_time().

Conclusion

If you want to measure the execution time accurately, you should use the time.perf_counter() method.