Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?
for example:
start = time.clock()
... do something
elapsed = (time.clock() - start)
vs.
start = time.time()
... do something
elapsed = (time.time() - start)
Use the time.time() is preferred.
Short answer: use time.clock() for timing in Python.
On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number.
time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value.
clock()
-> floating point numberReturn the CPU time or real time since the start of the process or since the first call to
clock()
. This has as much precision as the system records.time()
-> floating point numberReturn the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
Usually
time()
is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)Comparing test result between Ubuntu Linux and Windows 7.
On Ubuntu
On Windows 7
To extend on @Hill's results, here's a test using python 3.4.3 on Xubuntu 16.04 through wine:
(timeit.default_timer will use time.clock() because it sees the OS as 'win32')
when using Windows, clock() is usually more accurate, but this is not the case on wine...
you can see here time() is more accurate than clock(), which is usually the case with Linux and Mac.
For my own
practice. time()
has better precision thanclock()
on Linux.clock()
only has precision less than 10 ms. Whiletime()
gives prefect precision. My test is on CentOS 6.4, python 2.6using clock():