How to measure the duration of a function call or code block in python

Mon 06 July 2015 by Godson

Some times we may encounter the situation where we need to know total time taken by the function call. Here is the code which is pretty much handy and simple to measure the total time taken by the function(call)

import time

class MeasureDuration:
    def __init__(self):
    self.start = None
    self.end = None

    def __enter__(self):
    self.start = time.time()
    return self

    def __exit__(self, exc_type, exc_val, exc_tb):
    self.end = time.time()
    print "Total time taken: %s" % self.duration()

    def duration(self):
    return str((self.end - self.start) * 1000) + ' milliseconds'

Here is how you apply the above code to get the time taken by the function call

import time

def foo():
    time.sleep(1)

with MeasureDuration() as m:
   foo()    # We can place here the multiple calls or 
        # arbitary code block to measure

Output would look like as follows,

Total time taken: 1001.03282928 milliseconds