How to measure time with high-precision in Python?

PythonServer Side ProgrammingProgramming

To measure time with high precision, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes.


import time
t0= time.clock()
t1 = time.clock() - t0
print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)


This will give the output −

Time elapsed:  0.0009403145040156798

Note that different systems will have different accuracy based on their internal clock setup (ticks per second). but it's generally at least under 20ms. Also note that clock returns different things on different platforms. On Unix, it returns the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Published on 08-Jan-2018 11:04:56