views:

5121

answers:

9

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
+1  A: 

You could simply print the difference:

print tend - tstart
sth
+1  A: 

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:

from datetime import datetime

tstart = datetime.now()

# code to speed test

tend = datetime.now()
print tend - tstart

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.

Parvenu74
see second comment at the question level.
tyndall
+1  A: 

The following code should display the time detla...

from datetime import datetime

tstart = datetime.now()

# code to speed test

tend = datetime.now()
print tend - tstart
killy971
+2  A: 

time.time() / datetime is good for quick use, but is not always 100% precise. For that reason, I like to use one of the std lib profilers (especially hotshot) to find out what's what.

nilamo
+5  A: 

datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

You can do all sorts of maths with datetime.timedelta, eg:

>>> c / 10
datetime.timedelta(0, 0, 431654)

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.

Sharkey
+1  A: 

You could also use:

import time

start = time.clock()
do_something()
end = time.clock()
print "%.2gs" % (end-start)

Or you could use the python profilers.

Zitrax
+2  A: 

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.

Stefan Kendall
+6  A: 

You might want to use the timeit module instead.

Darius Bacon
+1: Excellent module
bortzmeyer
Cool. I'll check this out. +1
tyndall
+1  A: 

http://docs.python.org/library/timeit.html

awesome. thanks.
tyndall