Python

Measure execution time of a function in Python

February 28, 2022

Measure execution time of a function in Python

In this article we will learn how to measure the execution time of a function – using the time library, in a simple and effective way.

Measure execution time of a function cover

What’s up programmer, how are you? Let’s learn more about Python and also runtime.

The idea to measure the execution time is to use the Python time library, because it is the simplest and fastest way

Basically we are going to insert an instruction at the beginning and at the end of the function execution

Add these instructions to variables, and then at the end we can print the difference between the times

And we will have the execution time of the function

Shall we see it in practice?

import time

def myfunction():
 for i in range(1000):
  print("testing!")

beginning = time.time()

myfunction()

end = time.time()

print(end - beginning)

So we will receive a time in milliseconds, for example:

0.018824338912963867

And this is the runtime for the loopToAddTime() function

What can be done now is to convert this measure to seconds and represent it better for the user, since ms is not a very usual measure, nor is it visual.

Conclusion

In this article we learned how to measure execution time of a function

We use the time library, which gives us the possibility to use the time method

That inserted into a variable inserts code execution time at that point in the program

Making the difference between two points, we have the runtime

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x