Measuring the execution time of a Python program is useful for performance analysis, benchmarking, and optimization. Python provides several built-in modules to achieve this with ease. In this article, we'll explore different ways to measure how long a Python program takes to run.
Using the time Module
The time module provides a simple way to measure execution time by capturing timestamps before and after the code runs using time.time(). It returns the time in seconds since the epoch.
import time
start = time.time()
for i in range(5):
print("GeeksForGeeks")
time.sleep(1)
end = time.time()
print(f"Total runtime of the program is {end - start} seconds")
Output
GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks Total runtime of the program is 1.0009586811065674
Explanation:
- start stores the time before the loop starts and end captures the time after execution .
- loop prints a string 5 times.
- time.sleep(1) adds a 1-second pause to simulate delay.
- total runtime is printed as the difference between end and start.
Using the timeit Module
timeit module is specifically designed to measure the execution time of small code snippets with high precision. It avoids many common timing pitfalls.
import timeit
s = "from math import sqrt"
t = '''
def example():
mylist = []
for x in range(100):
mylist.append(sqrt(x))
example()
'''
print(timeit.timeit(setup=s, stmt=t, number=10000))
Output
0.08390588600002502
Explanation:
- s runs once to import necessary functions.
- t defines a small function that computes square roots.
- timeit.timeit() executes the code 10,000 times and returns the total time taken.
Using default_timer() from timeit
default_timer() function from the timeit module gives the most accurate clock depending on the platform. It is ideal for benchmarking small blocks of code.
from timeit import default_timer as timer
start = timer()
for _ in range(100):
s = "GeeksForGeeks"
end = timer()
print(end - start)
Output
6.883998139528558e-06
Explanation:
- timer() records high-precision start and end times.
- A loop runs 100 times with a basic assignment inside.
- The duration is printed as the difference between end and start.
Using the datetime Module
datetime module provides utilities to work with date and time. Using datetime.now() before and after execution allows you to measure duration in a readable format.
import datetime
start = datetime.datetime.now()
for _ in range(10_000_000):
statement = "GeeksForGeeks"
end = datetime.datetime.now()
print(end - start)
Output
0:00:00.588817
Explanation:
- start stores the current timestamp before the loop and end captures the time after execution.
- The loop performs a basic string assignment 10 million times.
- The duration is printed as a timedelta object.
Note: Output will vary depending on your system speed and CPU load.
Related articles: