How to measure function call duration in python

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

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

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


 

Output would look like as follows,


 

5 thoughts on “How to measure the duration of a function call or code block in python”

    1. Yes timeit is not having builtin context management. By default timeit won’t give us the time taken by the function or block of code unless we pass the number keyword argument 1. timeit will execute the given code block 1000000 times by default and will give us the total time take by the code block. To get exact time required by the code block we have to pass number keyword argument 1.
      timeit module is handy when we write micro optimized code. We can use it to choose best data structures and patterns according to their performance.

      Measuring time with the code snipped posted above.

      with MeasureDuration() as m:
      ....: time.sleep(1)
      ....:
      Total time taken: 1001.05214119 milliseconds

      Measuring time with timit module

      print "%s milliseconds" % (timeit.timeit("time.sleep(1)", "import time", number=1) * 1000)
      1001.0509491 milliseconds

Leave a Reply

Your email address will not be published. Required fields are marked *