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.
You could simply print the difference:
print tend - tstart
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.
Here is a custom function that mimic's Matlab's/Octave's tic
toc
functions.
Example of use:
time_var = time_me(); # get a variable with the current timestamp
... run operation ...
time_me(time_var); # print the time difference (e.g. '5 seconds 821.12314 ms')
Function :
def time_me(*arg):
if len(arg) != 0:
elapsedTime = time.time() - arg[0];
#print(elapsedTime);
hours = math.floor(elapsedTime / (60*60))
elapsedTime = elapsedTime - hours * (60*60);
minutes = math.floor(elapsedTime / 60)
elapsedTime = elapsedTime - minutes * (60);
seconds = math.floor(elapsedTime);
elapsedTime = elapsedTime - seconds;
ms = elapsedTime * 1000;
if(hours != 0):
print ("%d hours %d minutes %d seconds" % (hours, minutes, seconds))
elif(minutes != 0):
print ("%d minutes %d seconds" % (minutes, seconds))
else :
print ("%d seconds %f ms" % (seconds, ms))
else:
#print ('does not exist. here you go.');
return time.time()
You could use timeit like this to test a script named module.py
$ python -mtimeit -s 'import module'
datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds
>>> import datetime
>>> 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
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.
You might want to use the timeit module instead.