Python – Measure time taken by program to execute
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
# Code to Measure time taken by program to execute. import time # store starting time begin = time.time() # program body starts for i in range ( 5 ): print ( "w3wiki" ) # program body ends time.sleep( 1 ) # store end time end = time.time() # total time taken print (f "Total runtime of the program is {end - begin}" ) |
Output
w3wiki w3wiki w3wiki w3wiki w3wiki Total runtime of the program is 1.0009586811065674
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach #2 : Using Timeit module
Python3
# importing the required module import timeit # code snippet to be executed only once mysetup = "from math import sqrt" # code snippet whose execution time is to be measured mycode = ''' def example(): mylist = [] for x in range(100): mylist.append(sqrt(x)) ''' # timeit statement 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 = "w3wiki" 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 = "w3wiki" endTime = datetime.datetime.now() print (endTime - startTime) |
Output
0:00:00.588817
Note: Output may vary depending on the system or server load. To read more about Timeit modulule, refer – Timeit in Python with Examples