calculating system clock resolution

Tim Peters tim.peters at gmail.com
Sat Apr 8 08:45:38 EDT 2006


[jUrner]
>> def calc_time_res():
>>     now = time.time
>>     start = now()
>>     x = start
>>     while start == x:
>>         x = now()
>>     print x, start  # <--
>>     print x - start
>>
>> print calc_time_res()
>> 1.50203704834e-05
>>
>> Something is going wrong here.
>> If you look at the function ,time.time() returns time in microseconds
>> (most oses and so does mine).

Don't confuse resolution with precision (or make up other words you
like better ;-)):  just because some quantity is given with N bits
doesn't mean it's _accurate_ to N bits.    See below for a more
extreme example.

[Steven D'Aprano]
> ...
> This brings me to an even simpler method of getting the resolution of
> time.time(), without the overhead of a while loop:
>
> >>> abs(time.time() - time.time())
> 1.0013580322265625e-05
>
> which is approximately 0.01ms, just as you expected.

Caution:  the most likely outcome on Windows for that line is 0.0. 
That's because the clock mechanism underlying time.time() on Windows
only updates at a frequency of 18.2 Hz (older systems) or 64 Hz (newer
systems).  IOW, time.time() only "changes" 18.2 to 64 times per second
on Windows, and two consecutive calls are consequently likely to
return exactly the same result.

In contrast, time.clock() on Windows typically updates more than a
million times per second.



More information about the Python-list mailing list