High-resolution timers

David Lees debl2nonospammywhamm at bellatlantic.net
Thu Jan 17 00:00:00 EST 2002


Works pretty well on my Win98 box.

PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
>>> import time
>>> time.clock()
5.0285790911681387e-006
>>> time.clock()
5.1122890092022999
>>> time.clock()
9.3571322013443066

Also quite high resolution for timing running code.

import math, time

def timeIt(n):
    t0=time.clock()
    for i in xrange(n):
        j=math.sqrt(i)

    t1=time.clock()
    print 'loops = %d  total time = %f   time/loop = %f' %
(n,t1-t0,1e6*(t1-t0)/n)
 

Running this for loop counts that take a milliseconds
>>> loops = 1000  total time = 0.003536   time/loop = 3.535929
loops = 2000  total time = 0.007100   time/loop = 3.549758
loops = 3000  total time = 0.010510   time/loop = 3.503243
loops = 4000  total time = 0.013995   time/loop = 3.498634
loops = 5000  total time = 0.017825   time/loop = 3.564927
loops = 6000  total time = 0.020906   time/loop = 3.484386
loops = 7000  total time = 0.025111   time/loop = 3.587293
loops = 8000  total time = 0.027922   time/loop = 3.490253
loops = 9000  total time = 0.031517   time/loop = 3.501940


which shows that execution time measurements in the 10 millisecond range
are varying only about 2%, which could easily be due to other processes
running on my machine.

David Lees


Ben Wolfson wrote:
> 
> On Wed, 16 Jan 2002 21:32:42 -0600, Mark Hammond wrote:
> 
> > Use time.clock() - it will always provide the best timer for the
> > platform.
> 
> It acts pretty strangely on all the computers to which I have access:
> 
> harper:~> python
> Python 2.0 (#1, Feb 26 2001, 17:11:04) [C] on sunos5
> Type "copyright", "credits" or "license" for more information.
> >>> import time
> >>> print time.clock()
> 0.0
> >>> print time.clock()
> 0.01
> >>> print time.clock()
> 0.01
> >>> time.clock()
> 0.01
> >>> ^D
> harper:~> python
> Python 2.0 (#1, Feb 26 2001, 17:11:04) [C] on sunos5
> Type "copyright", "credits" or "license" for more information.
> >>> import time
> >>> time.clock()
> 0.0
> >>> print time.clock()
> 0.0
> >>> time.clock()
> 0.0
> >>> time.clock()
> 0.0
> >>> ^D
>



More information about the Python-list mailing list