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:
1 2 3 4 5 6 7 8 9 10 |
import time def sample_function(): # some operations here start_time = time.time() sample_function() end_time = time.time() print(f"Elapsed time: {end_time - start_time}") |
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:
1 2 3 4 5 6 7 8 |
import timeit def sample_function(): # some operations here pass execution_time = timeit.timeit(sample_function, number = 1000) print(f"Execution time: {execution_time}") |
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.
1 2 3 4 5 6 7 8 |
from timeit import Timer def sample_function(): # some operations here pass t = Timer(lambda: sample_function()) print(t.timeit()) |
Displaying Full Code
Below is the full code, combining all steps explained above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import time import timeit from timeit import Timer def sample_function(): # some operations here pass # using time module start_time = time.time() sample_function() end_time = time.time() print(f"Elapsed time using time module: {end_time - start_time}") # using timeit module execution_time = timeit.timeit(sample_function, number = 1000) print(f"Execution time using timeit module: {execution_time}") # using Timer Class from timeit t = Timer(lambda: sample_function()) print(f"Time using Timer class from timeit: {t.timeit()}") |
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.