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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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("GeeksForGeeks")
# 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}")

chevron_right


Output:

GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Total runtime of the program is 1.0010437965393066

 
Approach #2 : Using Timeit module



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

0.00119590759277

Note: Output may vary depending on the system or server load.

To read more about Timeit modulule, refer – Timeit in Python with Examples




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.