Dark Mode On/Off

# Calculate Time taken by a Program to Execute in Python

Posted in Programming   LAST UPDATED: MARCH 13, 2023

Time is precious. As programmers, we have to write programs that take less time to their execution. But to optimize our programs, we must first learn to calculate the time taken by a program for execution. In this tutorial, we are going to learn two different ways to calculate the execution time of a program in python.

## Method 1: Using the Time Module to Calculate the Execution Time of a Program

We have a method called `time()` in the time module in python, which can be used to get the current time. See the following steps to calculate the running time of a program using the `time()` function of the time module.

• Store the starting time before the first line of the program executes.

• Store the ending time after the last line of the program executes.

• The difference between the ending time and starting time will be the program's running time.

Let's have an example:

``````import time

# starting time
start = time.time()

# program body starts
for i in range(10):
print(i)

# sleeping for 1 sec to get 10 sec runtime
time.sleep(1)

# program body ends

# end time
end = time.time()

# total time taken
print(f"Runtime of the program is {end - start}")``````

Output:

``````0
1
2
3
4
5
6
7
8
9
Runtime of the program is 10.030879974365234```
```

We can calculate the running/execution time of any program using the following approach.

## Method 2: Use the timeit module to Calculate the Program Execution Time in Python

The `timeit()` method of the time it module can also be used to calculate the execution time of any program in python. The `timeit()` method accepts four arguments. Let's see what are these arguments:

1. setup, which takes the code which runs before the execution of the main program, the default value is pass
2. stmt, is a statement that we want to execute.
3. timer, is a `timeit.Timer` object, we don't have to pass anything to this argument.
4. number, which is the number of times the statement will run.

Let's take an example to understand this better:

``````import timeit

setup_code = "from math import factorial"

statement = """
for i in range(10):
factorial(i)
"""

print(f"Execution time is: {timeit.timeit(setup = setup_code, stmt = statement, number = 10000000)}")``````

Just for this program, we will be executing the above script 10000000 times just to increase the time of execution of the program.

Output:

```Execution time is 7.536292599999996
```

## Conclusion:

Calculating the time of execution of a program is very useful for optimizing your python script to perform better. The above two techniques can be useful when you have to optimize some complex algorithm written in python. If you have any doubts regarding the tutorial, please mention them in the comment section.

## You May Also Like

Want to learn coding?
Try our new interactive courses.
Over 20,000+ students enrolled.