Program to find the execution time of a program in Python

In this tutorial, we will learn how to find the execution time of a simple program that will calculate the factorial of a large number in the Python programming language? By Bipin Kumar Last updated : January 05, 2024

Execution time of a program

The execution time of a program is defined as the time spent by the system to execute the task.

Problem statement

Write a Python program to find the execution time of a program.

Finding the execution time of a program

As we all know any program takes some execution time but we don't know how much. So, don't worry, in this tutorial we will learn it by using the datetime module and also we will see the execution time for finding the factorial of a large number. A large number will be provided by the user and we have to calculate the factorial of a number, also we have to find the execution time of the factorial program. Before going to write the Python program, we will try to understand the algorithm.

Algorithm

The steps (algorithm) to find the execution time of a program (factorial program) are:

  1. Initially, we will import the datetime module and also the math module (to find the factorial) in the Program.
  2. Take the value of a number N from the user.
  3. Find the initial time by using now() function and assign it to a variable which is t_start.
  4. Calculate the factorial of a given number (N) and print it.
  5. Here, we will also find the current time and assign it to a variable which is t_end.
  6. To know the execution time simply find the difference between the t_end and t_start i.e t_end - t_start.

Now, let's start writing the Python program by simply implementing the above algorithm.

Python program to find the execution time of a program

# importing the modules
from datetime import datetime
import math

N = int(input("Enter the value of N: "))

t_start = datetime.now()
s = math.factorial(N)

print("factorial of the number:", s)

t_end = datetime.now()
e = t_end - t_start
print("The execution time for factorial program: ", e)

Output

The output of the above example is:

Enter the value of N: 25
factorial of the number: 15511210043330985984000000
The execution time for factorial program: 0:00:00.000022

The output format of the execution time of factorial as "hours: minutes: seconds. microseconds".

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.