time.perf_counter() function in Python
The time module provides various time-related functions. We must import the time module before using perf_counter() so we can access the function without throwing any errors.
The perf_counter() function always returns the float value of time in seconds. Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. In between this we can use time.sleep() and likewise functions.
Code #1: Understand the usage of the perf_counter .
# Python program to show time by perf_counter()
from time import perf_counter
# integer input from user, 2 input in single line
n, m = map(int, input().split())
# Start the stopwatch / counter
t1_start = perf_counter()
for i in range(n):
t = int(input()) # user gave input n times
if t % m == 0:
print(t)
# Stop the stopwatch / counter
t1_stop = perf_counter()
print("Elapsed time:", t1_stop, t1_start)
print("Elapsed time during the whole program in seconds:",
t1_stop-t1_start)
Output:
perf_counter_ns():
It always gives the integer value of time in nanoseconds. Similar to perf_counter(), but return time as nanoseconds.
Code #2: Usage of the perf_counter_ns and how to implement it.
# Python program to show time by
# perf_counter_ns()
from time import perf_counter_ns
# integer input from user, 2 input in single line
n, m = map(int, input().split())
# Start the stopwatch / counter
t1_start = perf_counter_ns()
for i in range(n):
t = int(input()) # user gave input n times
if t % m == 0:
print(t)
# Stop the stopwatch / counter
t1_stop = perf_counter_ns()
print("Elapsed time:", t1_stop, 'ns', t1_start, 'ns')
print("Elapsed time during the whole program in ns after n, m inputs:",
t1_stop-t1_start, 'ns')
Output:
Compare both the outputs of the program as perf_counter() returns in seconds and pers_counter_ns() returns in nanoseconds.
Advantages of perf_counter() :
1. perf_counter() will give you more precise value than time.clock() function .
2. From Python3.8 time.clock() function will be deleted and perf_counter will be used.
3. We can calculate float and integer both values of time in seconds and nanoseconds.
time.perf_counter() function in Python – FAQs
What does the time.time()
function do in Python?
The
time.time()
function returns the current time in seconds since the epoch (January 1, 1970, 00:00:00 UTC). It provides a floating-point number representing the time, which can be used to measure elapsed time or timestamp events.Example:
import time
current_time = time.time()
print(current_time) # Output: e.g., 1693455462.123456
How accurate is time.perf_counter()
?
The
time.perf_counter()
function provides a high-resolution timer with the highest available precision. It measures the time interval with a resolution of sub-second accuracy, making it suitable for performance measurements and benchmarking. The actual accuracy depends on the operating system and hardware but is generally very precise for most applications.Example:
import time
start_time = time.perf_counter()
# Code to measure
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(elapsed_time) # Output: e.g., 0.00234 (time in seconds)
How to count the time of a function in Python?
To count the time of a function, you can use the
time.perf_counter()
function to record the start and end times around the function call and compute the elapsed time.Example:
import time
def my_function():
# Function code
pass
start_time = time.perf_counter()
my_function()
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Function execution time: {elapsed_time:.6f} seconds")
How to measure performance time in Python?
To measure performance time in Python, use the
time.perf_counter()
function to measure elapsed time for code execution or functions. You can also use thetimeit
module for more structured performance testing.Example with
time.perf_counter()
:import time
start_time = time.perf_counter()
# Code to measure
end_time = time.perf_counter()
print(f"Performance time: {end_time - start_time:.6f} seconds")Example with
timeit
:import timeit
def my_function():
# Function code
pass
execution_time = timeit.timeit(my_function, number=1000)
print(f"Performance time: {execution_time:.6f} seconds for 1000 executions")
What is Counter()
in Python?
Counter()
is a class from thecollections
module that counts the occurrences of each element in an iterable, like a list or string. It returns a dictionary-like object where keys are elements and values are counts.Example:
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(data)
print(counter) # Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})Example with strings:
from collections import Counter
text = "hello world"
counter = Counter(text)
print(counter) # Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})