Learning how to measure the execution time of your code in Python can be extremely useful, especially in profiling and optimizing your code. This tutorial will guide you on how to start a timer in Python using the built-in time module.
Step 1: Import Time Module
The first step is to import Python’s built-in time module. You can do so with the following line of code:
1 |
import time |
Step 2: Start the Timer
Now that we have imported the time module, we can start a timer. To accomplish this, you can use the time() function from the time module:
1 |
start_time = time.time() |
This line basically fetches the current time in seconds since the epoch as a floating point number and assigns it to the variable start_time.
Step 3: Perform the Tasks
Between the starting and stopping of the timer, you can perform the tasks whose execution time you want to measure.
1 2 3 4 5 |
# perform tasks a = 5 b = 10 c = a + b print(c) |
Step 4: Stop the Timer
Once you have performed the tasks, you can stop the timer by again invoking the time() function and assigning it to a different variable:
1 |
end_time = time.time() |
Step 5: Calculate the Elapsed Time
Now that you have both the start and end times, you can calculate the elapsed time by subtracting the start time from the end time:
1 |
elapsed_time = end_time - start_time |
Now, elapsed_time holds the execution time of your tasks in seconds.
Putting It All Together
Here’s the full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import time # Start the timer start_time = time.time() # Perform tasks a = 5 b = 10 c = a + b print(c) # Stop the timer end_time = time.time() # Calculate the elapsed time elapsed_time = end_time - start_time print("Elapsed time: ", elapsed_time, "seconds") |
Conclusion
Starting and stopping a timer in Python is straightforward with Python’s built-in time module. With a few lines of code, you can accurately measure the execution time of your code or specific tasks within your code. This can be valuable for identifying bottlenecks and optimizing your Python programs.