我正在使用 Jupyter 笔记本。我正在尝试测量用 python 计算阿伏伽德罗数需要多长时间。我发现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')
Run Code Online (Sandbox Code Playgroud)
我的笔记本给出了 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')
Run Code Online (Sandbox Code Playgroud)
这给出了 2048.768273 秒。
Jon*_*lff 36
time.perf_counter()
睡觉时继续,time.process_time()
不会。
返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟以测量短持续时间。它确实包括睡眠期间经过的时间并且是系统范围的。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。
返回当前进程的系统和用户 CPU 时间总和的值(以秒为单位)。它不包括睡眠期间经过的时间。根据定义,它是流程范围的。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。
看官方文档
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
Run Code Online (Sandbox Code Playgroud)
小智 18
perf_counter() 应该测量一个进程花费的实际时间,就像你使用秒表一样。
process_time() 将为您提供计算机为当前进程花费的时间,具有操作系统的计算机通常不会在任何给定进程上花费 100% 的时间。这个计数器不应该计算 cpu 运行其他任何东西的时间。
大多数情况下 perf_counter 可能更可取,但如果您想比较代码效率, process_time 可能很有用。