How to use time.clock() function in python

Nick Craig-Wood nick at craig-wood.com
Tue Jan 23 13:30:08 EST 2007


yinglcs at gmail.com <yinglcs at gmail.com> wrote:
>  I am following this python example trying to time how long does an
>  operation takes, like this:
> 
>  My question is why the content of the file (dataFile) is just '0.0'?
>  I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str(
>  timeTaken)", but gives me 0.0.
>  Please tell me what am I missing?
> 
> 
>          t1 = time.clock()
>          os.system(cmd)
> 
>          outputFile = str(i) + ".png"
> 
>          t2 = time.clock()
> 
>          timeTaken = t2 - t1
>          allTimeTaken += timeTaken
>          print >>dataFile, timeTaken

Under unix, time.clock() measures CPU time used by the current
process.  os.system() will consume almost zero CPU while it waits for
the command you ran to finish.

You probably want time.time(), eg

  >>> from time import clock, time
  >>> print clock(), time()
  0.01 1169573460.96
  >>> print clock(), time()
  0.01 1169573463.76
  >>> print clock(), time()
  0.01 1169573467.09
  >>> 

However running the same under windows you get a quite different
result :-

  >>> from time import clock, time
  >>> print clock(), time()
  7.54285810068e-006 1169574534.84
  >>> print clock(), time()
  3.32073322168 1169574538.16
  >>> print clock(), time()
  7.32428004118 1169574542.15
  >>>

In windows clock() counts in real time and at much higher resolution
than time().

Under windows time() counts in 1ms steps wheras it usually counts in
1us steps under linux.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list