由于时间模块提供了各种与时间有关的功能。因此,有必要导入时间模块,否则会出错,因为时间模块中存在perf_counter()的定义。
perf_counter()函数始终以秒为单位返回时间的浮点值。返回性能计数器的值(以分数秒为单位),即具有最高可用分辨率的时钟以测量短时间。它确实包括睡眠期间经过的时间,并且为system-wide。返回值的参考点是不确定的,因此仅连续调用结果之间的差有效。在这之间,我们可以使用time.sleep()和类似的功能。
代码1:了解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)
输出:

pref_counter_ns():
它始终以纳秒为单位给出时间的整数值。与perf_counter()相似,但返回时间以纳秒为单位。
代码2:perf_counter_ns的用法以及如何实现。
# 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开始,将删除clock()函数,并使用perf_counter。
3.我们可以计算浮点数和整数时间值(以秒和纳秒为单位)。
本文详细介绍了Python中time模块的perf_counter()和perf_counter_ns()函数的使用方法及区别。前者以秒为单位返回高精度的时间计数,后者则以纳秒为单位。通过实例代码展示了如何利用这两个函数进行程序运行时间的精确测量。
2247

被折叠的 条评论
为什么被折叠?



