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)
On Unix time.clock() measures the amount of CPU time that has been used by the current process, so it's no good for measuring elapsed time from some point in the past. On Windows it will measure wall-clock seconds elapsed since the first call to the function. On either system time.time() will return seconds passed since the epoch.
If you're writing code that's meant only for Windows, either will work (though you'll use the two differently - no subtraction is necessary for time.clock()). If this is going to run on a Unix system or you want code that is guaranteed to be portable, you will want to use time.time().
As others have noted
time.clock()
is deprecated in favour oftime.perf_counter()
ortime.process_time()
, but Python 3.7 introduces nanosecond resolution timing withtime.perf_counter_ns()
,time.process_time_ns()
, andtime.time_ns()
, along with 3 other functions.These 6 new nansecond resolution functions are detailed in PEP 564:
As others have also noted, use the
timeit
module to time functions and small code snippets.Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provides NO accuracy because it may manage CPU time.
Others have answered re:
time.time()
vs.time.clock()
.However, if you're timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the
timeit
module.The difference is very platform-specific.
clock() is very different on Windows than on Linux, for example.
For the sort of examples you describe, you probably want the "timeit" module instead.
The short answer is: most of the time
time.clock()
will be better. However, if you're timing some hardware (for example some algorithm you put in the GPU), thentime.clock()
will get rid of this time andtime.time()
is the only solution left.Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, ...), this is worse with
time.time()
but exists also withtime.clock()
, so you should never run one timing test only, but always run a series of test and look at mean/variance of the times.