Fix Python – Python speed testing – Time Difference – milliseconds


Asked By – BuddyJoe

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 =
print t1

# code to speed test

tend =
print t2
# what am I missing?
# I'd like to print the time diff here

Now we will see solution for issue: Python speed testing – Time Difference – milliseconds


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

>>> import datetime
>>> a =
>>> b =
>>> c = b - a

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

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

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.

This question is answered By – NickZoic

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0