time.perf_counter() function in Python with examples
In this tutorial, we will learn about time.perf_counter() function in Python. Its function is to calculate the total execution time of any program.
It returns a float value (precise value of execution time).
It is helpful in comparing any two algorithms or checking if it is done under a given time. It also has many applications in various fields.
Calculating the execution time of a basic program
Creating an introductory program for printing the execution time as-
import time print(time.perf_counter())
Output:
18807.00947833
This is how we tried to print the execution time using time.perf_counter().
Calculating the execution time of Hello World
We will print and see what the execution time of this program is. Let’s move forward to the snippet part as-
import time
print("Hello World")
print(time.perf_counter())Output:
Hello World 5266.26077137
Calculate the execution time of a sum of two numbers
We will calculate the sum of two numbers and then print the execution time. Let’s try to print the execution time of this program-
import time a=9 b=10 c=0 c=a+b print(c) print(time.perf_counter())
Output:
19 2722.151702753
Calculate the execution time of the reverse of a number
We will reverse a number using the below algorithm and calculate its execution time-
import time
num = 1234
temp = num
rev = 0
while num > 0:
remainder = num % 10
rev = (rev * 10) + remainder
num = num // 10
print(rev)
print(time.perf_counter())Output:
4321 48953.407851554
This tutorial has a lot of information on this particular module to calculate the execution time. I hope you found this tutorial helpful. Thanks for reading!
Leave a Reply