How to check the execution time of Python script ?

16 Jul, 2021
In this article, we will discuss how to measure the running time of a Python Script. 
There are many python modules like time, timeit, and datetime in Python which can store the time at which the particular section of the program is being executed. By manipulating or getting the difference between times of beginning and ending at which a particular section is being executed we can calculate the time it took to execute the section. 
 
The following methods can be used to compute time difference:
 
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform-dependent.
Python datetime library defines a function that can be primarily used to get the current time and date. now() function Return the current local date and time, which is defined under datetime module.
timeit runs your snippet of code millions of times (default value is 1000000) so that you get the statistically most relevant measurement of code execution time.
 
Example 1: Computing the time using time module and time.time() function
 
Python3
# program to compute the time# of execution of any python codeimport time # we initialize the variable start# to store the starting time of# execution of programstart = time.time() # we can take any program but for# example we have taken the below# programa = 0for i in range(1000):    a += (i**100) # now we have initialized the variable# end to store the ending time after# execution of programend = time.time() # difference of start and end variables# gives the time of execution of the# program in betweenprint("The time of execution of above program is :", end-start)
Output:
The time of execution of above program is : 0.001995563507080078
We have computed the time of the above program which came out of the order 10^-3. We can check for the time by increasing the number of computations using the same algorithms.
Example 2: Checking times for execution of the program for different numbers of computations.
Python3
# program to compute the time# of execution of any python code# for different number of computationsimport time # we initialize a for loop and in each# iterations store the time of start# and end of the iterationsfor j in range(100, 1100, 100):    start = time.time()     # program to iterate the range of    # below loop increasing the value    # in each iterations    a = 0    for i in range(j):        a += (i**100)     # the end variable to store the    # ending time after execution of    # program after each iterations    end = time.time()     # difference of start and end variables    # gives the time of execution of the program    # in between in each iterations    print("Time for execution of program for {} order of computations: {}".format(        j, round(end-start, 10)))
Output:
We see a general trend in the increase in time of computation for an increase in the number of execution. However, it may not show any linear trend or fixed increments.
Example 3: Using datetime module in python and datetime.now function.
Python3
# program to compute the time of# execution of any python codefrom datetime import datetime # we initialize the variable start to# store the starting time of execution# of programstart = datetime.now() # we can take any program but for# example we have taken the below# programa = 0for i in range(1000):    a += (i**100) # now we have initialized the variable# end to store the ending time after# execution of programend = datetime.now() # difference of start and end variables# gives the time of execution of the# program in betweenprint("The time of execution of above program is :",      str(end-start)[5:])
Output:
The time of execution of above program is : 00.001996
Example 4: Using timeit
This would give us the execution time of any program. This module provides a simple way to find the execution time of small bits of Python code. It provides the timeit() method to do the same. The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments:
stmt which is the statement you want to measure; it defaults to ‘pass’.
setup which is the code that you run before running the stmt; it defaults to ‘pass’. We generally use this to import the required modules for our code.
timer which is a timeit.Timer object; it usually has a sensible default value so you don’t have to worry about it.
number which is the number of executions you’d like to run the stmt.
Python3
# program to compute the time of# execution of any python code using timit # importing the required moduleimport timeit # code snippet to be executed only oncemysetup = "from math import sqrt" # code snippet whose execution time# is to be measuredmycode = '''def example():    mylist = []    for x in range(100):        mylist.append(sqrt(x))''' # timeit statementprint ("The time of execution of above program is :",       timeit.timeit(setup = mysetup,                    stmt = mycode,                    number = 10000))
Output:
The time of execution of above program is : 0.0023286999994525104
simmytarika5
surinderdawra388
adnanirshad158
abhishek0719kadiyan
Picked
Python time-module
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list