time.time or time.clock

John Machin sjmachin at lexicon.net
Mon Jan 14 15:35:35 EST 2008


On Jan 15, 4:50 am, dwb... at gmail.com wrote:
> """
> <snipped>
> time.clock() isn't high enough resolution for Ubuntu, and time.time()
> isn't
> high enough resolution on windows.
>
> Take a look at datetime.  It is good to the micro-second on Linux and
> milli-second on Windows.
> """

On Windows, time.clock has MICROsecond resolution, but your method
appears to have exactly the same (MILLIsecond) resolution as
time.time, but with greater overhead, especially when the result is
required in seconds-and-a-fraction as a float:

>>> def datetimer(start=datetime.datetime(1970,1,1,0,0,0), nowfunc=datetime.datetime.now):
...     delta = nowfunc() - start
...     return delta.days * 86400 + delta.seconds +
delta.microseconds / 1000000.0
...
>>> tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
 diff))
['1200341583.484', '1200381183.484', '39600.0']
>>> tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
 diff))
['1200341596.484', '1200381196.484', '39600.0']
>>> tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
 diff))
['1200341609.4530001', '1200381209.4530001', '39600.0']
>>> tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
 diff))
['1200341622.562', '1200381222.562', '39600.0']
>>>

The difference of 39600 seconds (11 hours) would be removed by using
datetime.datetime.utcnow.

>
> import datetime
> begin_time=datetime.datetime.now()
> for j in range(100000):
>    x = j+1     # wait a small amount of time
> print "Elapsed time =", datetime.datetime.now()-begin_time
>
> ## You can also access the individual time values
> print begin_time.second
> print begin_time.microsecond     ## etc.

Running that on my Windows system (XP Pro, Python 2.5.1, AMD Turion 64
Mobile cpu rated at 2.0 GHz), I get
Elapsed time = 0:00:00.031000
or
Elapsed time = 0:00:00.047000
Using 50000 iterations, I get it down to 15 or 16 milliseconds. 15 ms
is the lowest non-zero interval that can be procured.

This is consistent with results obtained by using time.time.

Approach: get first result from timer function; call timer in a tight
loop until returned value changes; ignore the first difference so
found and save the next n differences.

Windows time.time appears to tick at 15 or 16 ms intervals, averaging
about 15.6 ms. For comparison, Windows time.clock appears to tick at
about 2.3 MICROsecond intervals.

Finally, some comments from the Python 2.5.1 datetimemodule.c:

/* No flavor of gettimeofday exists on this platform.  Python's
 * time.time() does a lot of other platform tricks to get the
 * best time it can on the platform, and we're not going to do
 * better than that (if we could, the better code would belong
 * in time.time()!)  We're limited by the precision of a double,
 * though.
 */

HTH,
John



More information about the Python-list mailing list