Time.clock (), Odd result when used inside a function definition
Using the following code (Python 3.3.x, WinXp):
## debug function in a general/personal debug include file.
def timer_compare(time1, time2='', note='@', time3=time.clock()):
print('time1',time1)
time2 = time.clock() ## same as the function-passed time.clock() (just a little later)
print('time2',time2)
print('time3',time3)
exit(321)
Caller ID used in the main code file:
time0 = time.clock()
## <other unrelated code.>
timer_compare(time0, time.clock())
I am getting the following output:
time1 0.0445(snip)
time2 0.0445(snip)
time3 0.0000043(snip) <- 4.385582001116343e-06
time3 here seems to have a low number path. (It looks like it was pulled from the timer we just created.)
What's going on here / what am I missing?
- I know that time.time () is generally recommended / recommended for .clock () times and why.
+3
source to share
1 answer
The default values ββare generated at definition time, not when called. A function timer_compare
is an object, and default values ββare evaluated when it is created and stored as an attribute of that object.
Since your function is created when your module is imported (or when your first script level is loaded by Python) the value time.clock()
will be very low.
Use a sentry instead:
def timer_compare(time1, time2='', note='@', time3=None):
if time3 is None:
time3 = time.clock()
+2
source to share