Kodeclik Blog

Measuring Elapsed Time in Python

Would you like to time your Python program to see how fast it runs? Learn about ways to measure elapsed time!
In this blogpost, we will learn about 3 different modules to help measure elapsed time in Python.

Method 1: Use the time module

The time module has a method called time() which returns the seconds since the beginning of the “epoch” (which is a system dependent time, but because it is fixed for your program, it serves the purpose of calculating elapsed time). Thus, we can invoke this method two times, once before the body of code we are timing and once after the body of code and we can subtract these two values to measure the elapsed time.
Here is a simple Python program to compute the elapsed time.
A sample output of the program will be:
Your specific numbers might vary. For instance when we run this program five times, here are the outputs we observed:
For this program, we are artificially running a loop for a million iterations (else the timer’s value would be really small). If you would like increased resolution, there is another method called “time_ns” which returns its value in nanoseconds since the epoch. Here is a modification to our earlier program that uses this method:
A sample output is:

Method 2: Use the timeit module

The timeit module is similar to time but its methods are named different. Here is how a timer program will look using this module (note that we have also modified the program to compute the sum of integers, so the times measured will be different):
The output is:
Again the results will be different for your computer and operating environment, and across different runs.

Method 3: Use the datetime module

The final method we would like to showcase is the datetime module. Unlike the first two methods, the datetime module gives the time in terms of days, hours, minutes, and seconds. As a result this module is more suitable for timing programs that run over multiple days or hours and where a user-friendly output is necessary.
Here is a program that uses the Datetime module. Note that we are also printing the start and end time using the datetime module’s format.
The output is:
Note that the start time and end time give all the day/hour/minute/second information and you are able to subtract start_time from end_time to obtain the second information.
We have seen three different methods for measuring elapsed time in your Python programs. Which one is your favorite?
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2022. All rights reserved.