How to Start a Timer in Python

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:

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:

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.

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:

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:

Now, elapsed_time holds the execution time of your tasks in seconds.

Putting It All Together

Here’s the full code:

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.