time in milliseconds by calling time.time()

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jul 25 02:18:23 EDT 2009


On Sat, 25 Jul 2009 07:47:14 +0200, Andre Engels wrote:

> On Sat, Jul 25, 2009 at 3:27 AM, Roy Smith<roy at panix.com> wrote:
> 
>> Keep in mind that while a float may have a large apparent precision,
>> there's no promise that the actual value returned by the OS has that
>> much precision.  You should be fine if all you're looking for is ms,
>> but I wouldn't count on much more than that.
> 
> Even stronger: I wouldn't count on _anything_ more than that. On my
> machine, time.time() changes value once per millisecond. I tested this
> by looking at a loop that recorded time.time() 100000 times. The total
> time in the loop was 61 ms; out of the 100000 numbers, 61 were higher
> than the previous one, with the highest difference being 1.00017 ms, the
> lowest 0.999928 ms.



I'm guessing you're running Windows, because for Windows time.time() has 
a low resolution and time.clock() is the higher resolution timer.

I'm running Linux, which is the opposite:


>>> from time import time, clock
>>> def diffs(alist):
...     deltas = []
...     for i in xrange(1, len(alist)):
...             deltas.append( alist[i] - alist[i-1] )
...     return deltas
...
>>> d = [time() for i in xrange(10000)]  # grab raw times
>>> dt = diffs(d)  # calculate the difference between each call
>>> max(dt), min(dt)
(0.00060892105102539062, 1.9073486328125e-06)
>>>
>>> d = [clock() for i in xrange(10000)]  # and again using clock()
>>> dc = diffs(d)
>>> max(dc), min(dc)
(0.010000000000000009, 0.0)

More important than the maximum and minimum time deltas is the resolution 
of ticks in each timer. Under Linux, clock() hardly ever gets updated:

>>> len(dc)  # how many time deltas?
9999
>>> len(filter(None, dc))  # how many non-zero deltas?
2

while time() gets updated frequently:

>>> len(dt)
9999
>>> len(filter(None, dt))
9999



See also the comments in the timeit module.



-- 
Steven



More information about the Python-list mailing list