python中perf_counter_Python time.perf_counter()用法及代码示例

由于时间模块提供了各种与时间有关的功能。因此,有必要导入时间模块,否则会出错,因为时间模块中存在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)

输出:

83467f5ed16592f7d195462eb95c2fcb.png

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

输出:

e533c7159e60cfa0be4edb5f178a2bc1.png

比较程序的两个输出,因为perf_counter()以秒为单位返回,pers_counter_ns()以纳秒为单位返回。

perf_counter()的优点:

1. perf_counter()会比time.clock()功能。

2.从Python3.8开始,将删除clock()函数,并使用perf_counter。

3.我们可以计算浮点数和整数时间值(以秒和纳秒为单位)。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值