8 Jul 2008

benchmark Python algorithms

there are several useful methods in the python library module 'time'
we can use them to benchmark our code segements or the algorithms.
the typical uses like:

>>> import time
>>> t=time.clock()
>>> t
4.4698418374402335e-006

>>> t=time.clock()
>>> time.clock()-t
6.635907915670856

>>> t=time.time()
>>> time.time()-t
5.0940001010894775
>>>

As we know from the code segemets posted above, we can use both clock() and time() methods to measure the time slice. However, there are still some differences between them, following is copied from the official documents:
clock( )
On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of ``processor time'', depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


and for the time():
time( )
Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

If we just read the definitions of these two method, we would think that the clock()'s precision is better than time()'s. But if you run the code offered above, you will found that time() has more usefull number than clock(). I don't know why at these moment.

For more details, please read:
http://docs.python.org/lib/module-time.html

No comments :

Post a Comment