time.time or time.clock

John Machin sjmachin at lexicon.net
Sun Jan 13 16:50:25 EST 2008


On Jan 14, 7:05 am, Ron Adam <r... at ronadam.com> wrote:
> I'm having some cross platform issues with timing loops.  It seems
> time.time is better for some computers/platforms and time.clock others, but

Care to explain why it seems so?

> it's not always clear which, so I came up with the following to try to
> determine which.
>
>     import time
>
>     # Determine if time.time is better than time.clock
>     # The one with better resolution should be lower.
>     if time.clock() - time.clock() < time.time() - time.time():
>         clock = time.clock
>     else:
>         clock = time.time
>
> Will this work most of the time, or is there something better?
>

Manual:
"""
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.
[snip]

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.
"""

AFAICT that was enough indication for most people to use time.clock on
all platforms ... before the introduction of the timeit module; have
you considered it?

It looks like your method is right sometimes by accident. func() -
func() will give a negative answer with a high resolution timer and a
meaningless answer with a low resolution timer, where "high" and "low"
are relative to the time taken for the function call, so you will pick
the high resolution one most of the time because the meaningless
answer is ZERO (no tick, no change). Some small fraction of the time
the low resolution timer will have a tick between the two calls and
you will get the wrong answer (-big < -small). In the case of two
"low" resolution timers, both will give a meaningless answer and you
will choose arbitrarily.

HTH,
John



More information about the Python-list mailing list