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?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.