Tuesday, January 12, 2016

Python measuring and printing elapsed time

In order to benchmark the return times of some hardware interface code, I needed to print elapsed times from different parts of the code. Super easy to do in python, just use variable_x = datetime.datetime.now() to get datetime variables at different places in the code, and you can just directly subtract them from each other to get variables of type datetime.timedelta which have a seconds and microseconds part.

variable_1 = datetime.datetime.now()
.
.
variable_2 = datetime.datetime.now()
delta = variable_2 - variable_1
print "elapsed time is %d seconds %d microseconds" % (delta.seconds, delta.microseconds)
print "or %.6f seconds" %((delta.seconds * 1000000 + delta.microseconds)/1000000.0)

Reference links:

http://stackoverflow.com/questions/766335/python-speed-testing-time-difference-milliseconds