我用的是Jupyter笔记本。我在试着测量用蟒蛇计算阿伏加德罗的数量需要多长时间。我发现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秒的时间。
发布于 2018-09-08 03:09:18
time.perf_counter() time.process_time() 会在睡眠期间继续工作,而 则不会。
time.perf_counter()→浮点数
返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,用于测量短持续时间。It 包括睡眠期间经过的时间,并且是系统范围的。返回值的参考点未定义,因此只有连续调用的结果之间的差异才有效。
time.process_time()→浮点数
返回当前进程的系统和用户CPU时间之和的值(以小数秒为单位)。It 不包括睡眠期间经过的时间。根据定义,它是进程范围的。返回值的参考点未定义,因此只有连续调用的结果之间的差异才有效。
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发布于 2020-10-17 19:22:19
perf_counter()应该测量进程实际花费的时间,就像您使用秒表一样。
process_time()会给出计算机在当前进程中花费的时间,有操作系统的计算机通常不会在任何给定的进程上花费100%的时间。此计数器不应计算cpu运行任何其他任务的时间。
大多数情况下,perf_counter可能更可取,但如果您想比较代码效率,process_time可能会很有用。
https://stackoverflow.com/questions/52222002
复制相似问题