gpt4 book ai didi

python-3.x - time.perf_counter() 和 time.process_time() 有什么区别?

转载 作者:行者123 更新时间:2023-12-04 11:07:26 26 4
gpt4 key购买 nike

我正在使用 Jupyter 笔记本。我正在尝试测量用 python 计算 Avogadro 的数字需要多长时间。我发现 time.perf_counter()time.process_time()模块将对此类工作很有用。所以我尝试了这两种方法,但结果完全不同。是什么造成了这种差异?这是我的代码。

import time

a = 10 ** 5

def AvogadroCounting():
i = 0
while i <= a:
i += 1

AvogadroCounting()

t_fract = time.perf_counter() #time to count fraction of avogadro's number in Seconds


print(t_fract, 'secs')

我的笔记本给出了 693920.393636181 秒。
import time

a = 10 ** 5

def AvogadroCounting():
i = 0
while i <= a:
i += 1

AvogadroCounting()

t_fract = time.process_time() #time to count fraction of avogadro's number in Seconds


print(t_fract, 'secs')

这给出了 2048.768273 秒。

最佳答案

time.perf_counter()在 sleep 中继续,time.process_time()才不是。

time.perf_counter() → float

返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟以测量短持续时间。它确实包括 sleep 期间耗时并且是系统范围的。返回值的引用点是未定义的,因此只有连续调用的结果之间的差异才有效。

time.process_time() → float

返回当前进程的系统和用户 CPU 时间之和的值(以秒为单位)。它不包括 sleep 期间耗时 .根据定义,它是进程范围的。返回值的引用点是未定义的,因此只有连续调用的结果之间的差异才有效。

official documentation

import time

def pc():
start = time.perf_counter()
time.sleep(1)
print(time.perf_counter()-start)

def pt():
start = time.process_time()
time.sleep(1)
print(time.process_time()-start)

pc() # 0.99872320449432
pt() # 0.0

关于python-3.x - time.perf_counter() 和 time.process_time() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52222002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com