📜  Python中的 time.perf_counter()函数

📅  最后修改于: 2022-05-13 01:55:45.104000             🧑  作者: Mango

Python中的 time.perf_counter()函数

时间模块提供各种与时间相关的功能。我们必须在使用 perf_counter() 之前导入 time 模块,以便我们可以访问该函数而不会引发任何错误。
perf_counter()函数始终以秒为单位返回时间的浮点值。返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟以测量短持续时间。它确实包括睡眠期间经过的时间,并且是系统范围的。返回值的参考点是未定义的,因此只有连续调用的结果之间的差异才有效。在这之间,我们可以使用time.sleep()和类似的函数。
代码 #1:了解perf_counter的用法。

Python3
# 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)


Python3
# 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')


输出:

pref_counter_ns():
它总是以纳秒为单位给出时间的整数值。类似于 perf_counter(),但返回时间为纳秒。
代码 #2: perf_counter_ns的用法以及如何实现它。

Python3

# 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')

输出:

比较程序的两个输出,因为 perf_counter() 以秒为单位返回,而 pers_counter_ns() 以纳秒为单位返回。
perf_counter() 的优点:
1. perf_counter() 会给你比 time.clock() 更精确的函数。
2. 从 Python3.8 开始,time.clock()函数将被删除,将使用 perf_counter。
3. 我们可以以秒和纳秒为单位计算浮点数和整数时间值。