473,703 Members | 3,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

time.time or time.clock


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
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?
Ron

Jan 13 '08 #1
9 8292
On Jan 14, 7:05 am, Ron Adam <r...@ronadam.c omwrote:
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 QueryPerformanc eCounter(). 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
Jan 13 '08 #2
John Machin wrote:
AFAICT that was enough indication for most people to use time.clock on
all platforms ...
which was unfortunate, given that time.clock() isn't even a proper clock
on most Unix systems; it's a low-resolution sample counter that can
happily assign all time to a process that uses, say, 2% CPU and zero
time to one that uses 98% CPU.
before the introduction of the timeit module; have you considered it?
whether or not "timeit" suites his requirements, he can at least replace
his code with

clock = timeit.default_ timer

which returns a good wall-time clock (which happens to be time.time() on
Unix and time.clock() on Windows).

</F>

Jan 13 '08 #3


John Machin wrote:
On Jan 14, 7:05 am, Ron Adam <r...@ronadam.c omwrote:
>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 QueryPerformanc eCounter(). 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?
I use it to time a Visual Python loop which controls frame rate updates and
set volocities according to time between frames, rather than frame count.
The time between frames depends both on the desired frame rate, and the
background load on the computer, so it isn't constant.

time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't
high enough resolution on windows.

I do use timeit for bench marking, but haven't tried using in a situation
like this.

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).
If the difference is between two high resolution timers then it will be
good enough. I think the time between two consectutive func() calls is
probably low enough to rule out low resolution timers.
In the case of two
"low" resolution timers, both will give a meaningless answer and you
will choose arbitrarily.
In the case of two low resolution timers, it will use time.time. In this
case I probably need to raise an exception. My program won't work
correctly with a low resolution timer.

Thanks for the feed back, I will try to find something more dependable.

Ron

Jan 14 '08 #4


John Machin wrote:
On Jan 14, 7:05 am, Ron Adam <r...@ronadam.c omwrote:
>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 QueryPerformanc eCounter(). 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?
I use it to time a Visual Python loop which controls frame rate updates and
set volocities according to time between frames, rather than frame count.
The time between frames depends both on the desired frame rate, and the
background load on the computer, so it isn't constant.

time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't
high enough resolution on windows.

I do use timeit for bench marking, but haven't tried using in a situation
like this.

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).
If the difference is between two high resolution timers then it will be
good enough. I think the time between two consectutive func() calls is
probably low enough to rule out low resolution timers.
In the case of two
"low" resolution timers, both will give a meaningless answer and you
will choose arbitrarily.
In the case of two low resolution timers, it will use time.time. In this
case I probably need to raise an exception. My program won't work
correctly with a low resolution timer.

Thanks for the feed back, I will try to find something more dependable.

Ron

Jan 14 '08 #5


Fredrik Lundh wrote:
John Machin wrote:
>AFAICT that was enough indication for most people to use time.clock on
all platforms ...

which was unfortunate, given that time.clock() isn't even a proper clock
on most Unix systems; it's a low-resolution sample counter that can
happily assign all time to a process that uses, say, 2% CPU and zero
time to one that uses 98% CPU.
before the introduction of the timeit module; have you considered it?

whether or not "timeit" suites his requirements, he can at least replace
his code with

clock = timeit.default_ timer

which returns a good wall-time clock (which happens to be time.time() on
Unix and time.clock() on Windows).

Thanks for the suggestion Fredrik, I looked at timeit and it does the
following.
import sys
import time

if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time

I was hoping I could determine which to use by the values returned. But
maybe that isn't as easy as it seems it would be.
Ron

Jan 14 '08 #6


Fredrik Lundh wrote:
John Machin wrote:
>AFAICT that was enough indication for most people to use time.clock on
all platforms ...

which was unfortunate, given that time.clock() isn't even a proper clock
on most Unix systems; it's a low-resolution sample counter that can
happily assign all time to a process that uses, say, 2% CPU and zero
time to one that uses 98% CPU.
before the introduction of the timeit module; have you considered it?

whether or not "timeit" suites his requirements, he can at least replace
his code with

clock = timeit.default_ timer

which returns a good wall-time clock (which happens to be time.time() on
Unix and time.clock() on Windows).

Thanks for the suggestion Fredrik, I looked at timeit and it does the
following.
import sys
import time

if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time

I was hoping I could determine which to use by the values returned. But
maybe that isn't as easy as it seems it would be.
Ron
Jan 14 '08 #7
"""
<snipped>
time.clock() isn't high enough resolution for Ubuntu, and time.time()
isn't
high enough resolution on windows.

Take a look at datetime. It is good to the micro-second on Linux and
milli-second on Windows.
"""

import datetime
begin_time=date time.datetime.n ow()
for j in range(100000):
x = j+1 # wait a small amount of time
print "Elapsed time =", datetime.dateti me.now()-begin_time

## You can also access the individual time values
print begin_time.seco nd
print begin_time.micr osecond ## etc.
Jan 14 '08 #8
dw****@gmail.co m wrote:
"""
<snipped>
time.clock() isn't high enough resolution for Ubuntu, and time.time()
isn't high enough resolution on windows.

Take a look at datetime. It is good to the micro-second on Linux and
milli-second on Windows.
datetime.dateti me.now() does the same thing as time.time(); it uses the
gettimeofday() API for platforms that have it (and so does time.time()),
and calls the fallback implementation in time.time() if gettimeofdat()
isn't supported. from the datetime sources:

#ifdef HAVE_GETTIMEOFD AY
struct timeval t;
#ifdef GETTIMEOFDAY_NO _TZ
gettimeofday(&t );
#else
gettimeofday(&t , (struct timezone *)NULL);
#endif
...
#else /* ! HAVE_GETTIMEOFD AY */

/* No flavor of gettimeofday exists on this platform. Python's
* time.time() does a lot of other platform tricks to get the
* best time it can on the platform, and we're not going to do
* better than that (if we could, the better code would belong
* in time.time()!) We're limited by the precision of a double,
* though.
*/

(note the "if we could" part).

</F>

Jan 14 '08 #9
On Jan 15, 4:50 am, dwb...@gmail.co m wrote:
"""
<snipped>
time.clock() isn't high enough resolution for Ubuntu, and time.time()
isn't
high enough resolution on windows.

Take a look at datetime. It is good to the micro-second on Linux and
milli-second on Windows.
"""
On Windows, time.clock has MICROsecond resolution, but your method
appears to have exactly the same (MILLIsecond) resolution as
time.time, but with greater overhead, especially when the result is
required in seconds-and-a-fraction as a float:
>>def datetimer(start =datetime.datet ime(1970,1,1,0, 0,0), nowfunc=datetim e.datetime.now) :
.... delta = nowfunc() - start
.... return delta.days * 86400 + delta.seconds +
delta.microseco nds / 1000000.0
....
>>tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
diff))
['1200341583.484 ', '1200381183.484 ', '39600.0']
>>tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
diff))
['1200341596.484 ', '1200381196.484 ', '39600.0']
>>tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
diff))
['1200341609.453 0001', '1200381209.453 0001', '39600.0']
>>tt = time.time(); td = datetimer(); diff = td - tt; print map(repr, (tt, td,
diff))
['1200341622.562 ', '1200381222.562 ', '39600.0']
>>>
The difference of 39600 seconds (11 hours) would be removed by using
datetime.dateti me.utcnow.
>
import datetime
begin_time=date time.datetime.n ow()
for j in range(100000):
x = j+1 # wait a small amount of time
print "Elapsed time =", datetime.dateti me.now()-begin_time

## You can also access the individual time values
print begin_time.seco nd
print begin_time.micr osecond ## etc.
Running that on my Windows system (XP Pro, Python 2.5.1, AMD Turion 64
Mobile cpu rated at 2.0 GHz), I get
Elapsed time = 0:00:00.031000
or
Elapsed time = 0:00:00.047000
Using 50000 iterations, I get it down to 15 or 16 milliseconds. 15 ms
is the lowest non-zero interval that can be procured.

This is consistent with results obtained by using time.time.

Approach: get first result from timer function; call timer in a tight
loop until returned value changes; ignore the first difference so
found and save the next n differences.

Windows time.time appears to tick at 15 or 16 ms intervals, averaging
about 15.6 ms. For comparison, Windows time.clock appears to tick at
about 2.3 MICROsecond intervals.

Finally, some comments from the Python 2.5.1 datetimemodule. c:

/* No flavor of gettimeofday exists on this platform. Python's
* time.time() does a lot of other platform tricks to get the
* best time it can on the platform, and we're not going to do
* better than that (if we could, the better code would belong
* in time.time()!) We're limited by the precision of a double,
* though.
*/

HTH,
John
Jan 14 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3404
by: peterbe | last post by:
What's the difference between time.clock() and time.time() (and please don't say clock() is the CPU clock and time() is the actual time because that doesn't help me at all :) I'm trying to benchmark some function calls for Zope project and when I use t0=time.clock(); foo(); print time.clock()-t0 I get much smaller values than when I use time.clock() (most of them 0.0 but some 0.01) When I use time.time() I get values like...
6
3748
by: cournape | last post by:
Hi there, I have some scientific application written in python. There is a good deal of list processing, but also some "simple" computation such as basic linear algebra involved. I would like to speed things up implementing some of the functions in C. So I need profiling. I first tried to use the default python profiler, but profiling my application multiplies the execution time by a factor between 10 and 100 ! So I decided to give a...
9
7283
by: HL | last post by:
I am using VS 2005 Beta - C# Problem: The Timer fires a few milliseconds before the actual Due-Time Let's say a timer is created in the following manner: System.Threading.Timer m_timer = null; Let's declare a constant Int32 m_TimePeriod = 10000;
17
6425
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional.
5
4117
by: raybakk | last post by:
Hi there. If I make a function in c (I acually use gnu right now), is there any way to find out how many clocksycluses that function takes? If I divide some numbers etc Var1 = Var2/Var3, is it a fix amount of clocksycluses that is been used for that division, or does it varies? Raymond
7
7672
by: nono909 | last post by:
I wrote the following time class for the following assignment.i need help in completing this program pleasee. Write a class to hold time. Time is the hour, minute and seconds. Write a constructor that will allow the user of your class to initialize a time or set the time to all zeros if not initialized. Include all the operators listed above. Your program will need to read from a file of times and commands. There will be a number at the top...
5
5643
by: yinglcs | last post by:
Hi, 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?
37
4680
by: David T. Ashley | last post by:
I have Red Hat Enterprise Linux 4. I was just reading up about UTC and leap seconds. Is it true on my system that the Unix time may skip up or down by one second at midnight when there is a leap second? By "Unix time" I mean the integer returned by time() and similar functions. I'm concerned about the "down" case. Some of the software I've written
8
1849
by: Theo v. Werkhoven | last post by:
hi, In this code I read out an instrument during a user determined period, and save the relative time of the sample (since the start of the test) and the readback value in a csv file. #v+ from datetime import * from time import * from visa import *
0
9122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8966
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4433
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3125
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.