How to measure elapsed time under Windows?

Paul McGuire ptmcg at austin.rr.com
Wed Feb 10 01:41:46 EST 2010


On Feb 9, 10:10 am, Grant Edwards <inva... at invalid.invalid> wrote:
> Is there another way to measure small periods of elapsed time
> (say in the 1-10ms range)?
>
On Feb 9, 10:10 am, Grant Edwards <inva... at invalid.invalid> wrote:
> Is there another way to measure small periods of elapsed time
> (say in the 1-10ms range)?
>

I made repeated calls to time.clock() in a generator expression, which
is as fast a loop I can think of in Python.  Then I computed the
successive time deltas to see if any granularities jumped out.  Here
are the results:

>>> import time
>>> from itertools import groupby
>>>
>>> # get about 1000 different values of time.clock()
>>> ts = set(time.clock() for i in range(1000))
>>>
>>> # sort in ascending order
>>> ts = sorted(ts)
>>>
>>> # compute diffs between adjacent time values
>>> diffs = [j-i for i,j in zip(ts[:-1],ts[1:])]
>>>
>>> # sort and group
>>> diffs.sort()
>>> diffgroups = groupby(diffs)
>>>
>>> # print the distribution of time differences in microseconds
>>> for i in diffgroups: print "%3d %12.6f" % (len(list(i[1])), i[0]*1e6)
...
 25     2.234921
 28     2.234921
242     2.514286
506     2.514286
 45     2.793651
116     2.793651
  1     3.073016
  8     3.073016
  6     3.352381
  4     3.631746
  3     3.911112
  1     3.911112
  5     4.190477
  2     4.469842
  1     6.146033
  1     8.660319
  1     9.777779
  1    10.895239
  1    11.174605
  1    24.304765
  1    41.904767

There seems to be a step size of about .28 microseconds.  So I would
guess time.clock() has enough resolution.  But also beware of the
overhead of the calls to clock() - using timeit, I find that each call
takes about 2 microseconds (consistent with the smallest time
difference in the above data set).

-- Paul



More information about the Python-list mailing list