Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.
timeit seems to be capable of high-precision time measurement, but rather than measure how long a code snippet takes, I'd like to directly access the time values.
Python tries hard to use the most precise time function for your platform to implement
time.time()
:( from http://svn.python.org/view/python/trunk/Modules/timemodule.c?revision=81756&view=markup )
I observed that the resolution of time.time() is different between Windows 10 Professional and Education versions.
On a Windows 10 Professional machine, the resolution is 1 ms. On a Windows 10 Education machine, the resolution is 16 ms.
Fortunately, there's a tool that increases Python's time resolution in Windows: https://vvvv.org/contribution/windows-system-timer-tool
With this tool, I was able to achieve 1 ms resolution regardless of Windows version. You will need to be keep it running while executing your Python codes.
David's post was attempting to show what the clock resolution is on Windows. I was confused by his output, so I wrote some code that shows that
time.time()
on my Windows 8 x64 laptop has a resolution of 1 msec:Which outputs:
And a way to do a 1000 sample average of the delta:
Which output on two consecutive runs:
So
time.time()
on my Windows 8 x64 has a resolution of 1 msec.A similar run on
time.clock()
returns a resolution of 0.4 microseconds:Returns:
Which is ~
0.4e-06
An interesting thing about
time.clock()
is that it returns the time since the method was first called, so if you wanted microsecond resolution wall time you could do something like this:(which would probably drift after a while, but you could correct this occasionally, for example
dc > 3600
would correct it every hour)You can also use time.clock() It counts the time used by the process on Unix and time since the first call to it on Windows. It's more precise than time.time().
It's the usually used function to measure performance.
Just call
EDITED: Ups, I miss the question as you want to know exactly the time, not the time spent...
The comment left by tiho on Mar 27 '14 at 17:21 deserves to be its own answer:
Python 3.7 introduces 6 new time functions with nanosecond resolution, for example instead of
time.time()
you can usetime.time_ns()
:These 6 functions are described in PEP 564: