Python – Measure time taken by program to execute
Last Updated :
14 Mar, 2023
This article aims to show how to measure the time taken by the program to execute. Calculating time helps to optimize your Python script to perform better.
Approach #1 :
A simple solution to it is to use time module to get the current time. The following steps calculate the running time of a program or section of a program.
- Store the starting time before the first line of the program executes.
- Store the ending time after the last line of the program executes.
- Print the difference between start time and end time.
Code #1 :
Python3
import time
begin = time.time()
for i in range ( 5 ):
print ( "GeeksForGeeks" )
time.sleep( 1 )
end = time.time()
print (f "Total runtime of the program is {end - begin}" )
|
Output
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Total runtime of the program is 1.0009586811065674
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach #2 : Using Timeit module
Python3
import timeit
mysetup = "from math import sqrt"
mycode =
print timeit.timeit(setup = mysetup, stmt = mycode, number = 10000 )
|
Output:
0.00119590759277
Approach #3 : Using default_timer() method in timeit module
Python3
import timeit
startTime = timeit.default_timer()
for _ in range ( 100 ):
statement = "GeeksForGeeks"
endTime = timeit.default_timer()
print (endTime - startTime)
|
Output
1.2153992429375648e-05
Approach #4 : Using the datetime module
Python3
import datetime
startTime = datetime.datetime.now()
for _ in range ( 1_00_00_000 ):
statement = "GeeksForGeeks"
endTime = datetime.datetime.now()
print (endTime - startTime)
|
Note: Output may vary depending on the system or server load. To read more about Timeit modulule, refer – Timeit in Python with Examples
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...