How to check the execution time of Python script ?
Last Updated :
26 Apr, 2023
In this article, we will discuss how to check the execution time of a Python script.
There are many Python modules like time, timeit and datetime module in Python which can store the time at which a 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:
- Python time module provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of the Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform-dependent.
- Python datetime module 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 the datetime module.
- Python timeit module runs your snippet of code n number of times (the default value is, 1000000) so that you get the statistically most relevant measurement of code execution time.
Using the time module check the execution time of Python
Example 1: Measuring time taken for a code segment by recording start and end times
Computing the time using the time module and time.time() function. 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.
Python3
# Import time module
import time
# record start time
start = time.time()
# define a sample code segment
a = 0
for i in range(1000):
a += (i**100)
# record end time
end = time.time()
# print the difference between start
# and end time in milli. secs
print("The time of execution of above program is :",
(end-start) * 10**3, "ms")
Output:
The time of execution of above program is : 0.77056884765625 ms
Example 2: Measuring time taken for a code segment by adding up the time required per iteration
Checking times for execution of the program for different numbers of computations. 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.
Python3
# import time module
import time
# create sample code for testing
for j in range(100, 5501, 100):
# store iteration start timestamp
start = time.time()
a = 0
for i in range(j):
a += (i**100)
# store iteration end timestamp
end = time.time()
# show time of execution per iteration
print(f"Iteration: {j}\tTime taken: {(end-start)*10**3:.03f}ms")
Output:
Iteration: 100 Time taken: 0.105ms
Iteration: 200 Time taken: 0.191ms
Iteration: 300 Time taken: 0.291ms
Iteration: 400 Time taken: 0.398ms
Iteration: 500 Time taken: 0.504ms
Iteration: 600 Time taken: 0.613ms
Iteration: 700 Time taken: 0.791ms
...
Iteration: 5400 Time taken: 6.504ms
Iteration: 5500 Time taken: 6.630ms
Explanation: Here we have truncated the output for representation purpose. But if we compare the iterations from 100 to 700 they are less than 1ms. But towards the end of the loop, each iteration taking ~7ms. Thus, there is an increase in time taken as the number of iterations have increased. This is generally because, the inner loop iterate more number of time depending on each outer iteration.
Using the DateTime module check the execution time
Using the datetime module in Python and datetime.now() function to record timestamp of start and end instance and finding the difference to get the code execution time.
Python3
from datetime import datetime
# record current timestamp
start = datetime.now()
# create loop-setup for testing
a = 0
for i in range(1000):
a += (i**100)
# record loop end timestamp
end = datetime.now()
# find difference loop start and end time and display
td = (end - start).total_seconds() * 10**3
print(f"The time of execution of above program is : {td:.03f}ms")
Output:
The time of execution of above program is : 0.766ms
Using timeit module check the execution time
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; usually has a sensible default value, so you don’t have to worry about it.
- The number, which is the number of executions you’d like to run the stmt.
Example 1: Using timeit inside Python code snippet to measure execution time
Python3
# importing the required module
import timeit
# code snippet to be executed only once
# before the stmt parameter in timeit
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
exec_time = timeit.timeit(stmt=mycode,
setup=mysetup,
number=1000000) * 10**3
print(f"The time of execution of above program is : {exec_time:.03f}ms")
Output:
The time of execution of above program is : 71.161ms
Example 2: Using timeit from command line to measure execution time
We can measure time taken by simple code statements without the need to write new Python files, using timeit CLI interface.
timeit supports various command line inputs, Here we will note a few of the mos common arguments:
- -s [--setup]: Setup code to run before running the code statement.
- -n [--number]: Number of times to execute the statement.
- -p [--process]: Measure the process time of the code execution, instead of the wall-clock time.
- Statement: The code statements to test the execution time, taken as a positional argument.
timeit CLI statement:
python -m timeit -s "import random" "l = [x**9 for x in range(random.randint(1000, 1500))]"
Output:
500 loops, best of 5: 503 used per loop
Similar Reads
How to Minimize Python Script Execution Time? Minimizing Python script execution time is essential for improving performance, especially in production environments, competitive programming (CP) or data structures and algorithms (DSA). Faster execution ensures better user experience in apps and helps us perform well in coding challenges. In this
3 min read
How to Measure Script Execution Time in PHP? Measuring the script execution time in PHP is the time required to execute the PHP script. To calculate script execution time use clock time rather than the CPU execution time. Measuring script execution time is useful to check and improve the execution time for better application performance.Measur
2 min read
Python Script to check PC last reboot time psutil is a cross-platform library for retrieving information on running processes and system utilization(CPU, memory, disks, networks, sensors) in Python. The Python script below can be run in both Windows and Linux. psutil library can be installed using the terminal by: In Windows: pip install psu
1 min read
Python | time.clock_settime_ns() method time.clock_settime_ns() method of Time module is used to set the time (in nanoseconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock. This method is similar to time.clock_settime() method which is used to set time of the specified clock clk_
2 min read
Python | How to time the program This article aims to show how to calculate the time it takes to perform various tasks. A simple solution to it is to use time module. This module contains various time-related functions. Also it's very useful to put a higher-level interface over these functions and use them as a stop-watch as explai
2 min read
Python | time.clock_settime() method time.clock_settime() method of Time module is used to set the time (in seconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock. Syntax: time.clock_settime(clk_id, seconds) Parameters: clk_id: A clk_id constant or an integer value representing
1 min read
How does the Python Interpreter check thread duration? In Python, threads are a means of achieving concurrent execution. The Python interpreter employs a mechanism to manage and monitor the duration and execution of threads. Understanding how the Python interpreter handles thread duration is essential for developing efficient and responsive multithreade
3 min read
Python IMDbPY â Getting run time of the series In this article we will see how we can get the run time of the series, run time is basically the time for which how long each episode run is of series basically run time is the length i.e how long each episode is in minutes. In order to get this we have to do the following - 1. Get the series detail
2 min read
Getting the time since OS startup using Python Uptime is the time elapsed since the Operating system started. Operating systems have discrete mechanisms to keep track of this time, which they further utilize for performing OS related tasks. This time is particularly useful for certain applications such as:- Usage Tracking ApplicationsBackup Appl
3 min read
How to obtain the time taken for a method to be executed in TestNG? TestNG (Test Next Generation) is a popular testing framework in Java used for unit testing, integration testing, and more. One of the frequent requirements during testing is to measure the time taken by a particular method to execute. Tracking execution time is essential for performance testing, ens
4 min read