What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
# what am I missing?
# I'd like to print the time diff here
The following code should display the time detla...
You may want to look into the profile modules. You'll get a better read out of where your slowdowns are, and much of your work will be full-on automated.
datetime.timedelta
is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microsecondsBe aware that
c.microseconds
only returns the microseconds portion of the timedelta! For timing purposes always usec.total_seconds()
.You can do all sorts of maths with datetime.timedelta, eg:
It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.
You might want to use the timeit module instead.
I know this is late, but I actually really like using:
time.time()
gives you seconds since the epoch. Because this is a standardized time in seconds, you can simply subtract the start time from the end time to get the process time (in seconds).time.clock()
is good for benchmarking, but I have found it kind of useless if you want to know how long your process took. For example, it's much more intuitive to say "my process takes 10 seconds" than it is to say "my process takes 10 processor clock units"In the first example above, you are shown a time of 0.05 for time.clock() vs 0.06377 for time.time()
In the second example, somehow the processor time shows "0" even though the process slept for a second.
time.time()
correctly shows a little more than 1 second.I am not a Python programmer, but I do know how to use Google and here's what I found: you use the "-" operator. To complete your code:
Additionally, it looks like you can use the strftime() function to format the timespan calculation in order to render the time however makes you happy.