How to Time a Function in Python

Timing your functions in Python can be a critical task, especially when you are working on optimizing your code or dealing with performance-sensitive tasks. In this tutorial, we will cover how to time a function in Python. We will be looking into various methods like using Python’s built-in time module, timeit module, and more.

Step 1: Using the Time Module

Python’s built-in Time module provides a function time(), which returns the current system time in seconds since the epoch (as a floating point number). This can be used to compute elapsed time.

Here is a sample code:

Step 2: Using the Timeit Module

Python also provides a more precise way to measure the execution time of small bits of Python code. It has both a command-line interface and a callable one. The timeit module avoids various issues that can negatively impact the accuracy of time.time().

Here is an example of how the timeit module can be used to time a function:

Step 3: Use Timer Class from Timeit

The Timer class from the timeit module can also be used. The timer is more flexible than the timeit() function. It allows you to create a Timer object around the statement to be timed, and then call methods on it.

Displaying Full Code

Below is the full code, combining all steps explained above:

Conclusion

Python provides several built-in modules for timing your functions such as Time and Timeit. Time module is more suitable for measuring time intervals during program’s run while Timeit provides a simple way to time small bits of Python code. It has both a callable interface and a command-line interface and avoids a number of common traps for measuring execution times. Always choose the right tool that applies to your need for accurate and desired results.