The simple way to measure the duration of function call in python using context management.
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 duration of function call or time taken by the function(call) in python
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
The post How to measure the duration of a function call or code block in python appeared first on Lintel Technologies Blog.