首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >time.perf_counter()和time.process_time()有什么区别?

time.perf_counter()和time.process_time()有什么区别?
EN

Stack Overflow用户
提问于 2018-09-07 19:52:14
回答 2查看 17.8K关注 0票数 33

我用的是Jupyter笔记本。我在试着测量用蟒蛇计算阿伏加德罗的数量需要多长时间。我发现time.perf_counter()time.process_time()模块对这类工作很有用。所以我尝试了这两种方法,但结果完全不同。是什么造成了这种不同?这是我的代码。

代码语言:javascript
复制
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秒。

代码语言:javascript
复制
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秒的时间。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-08 03:09:18

time.perf_counter() time.process_time() 会在睡眠期间继续工作,而 则不会。

time.perf_counter()→浮点数

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

time.process_time()→浮点数

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

请参阅official documentation

代码语言:javascript
复制
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
票数 44
EN

Stack Overflow用户

发布于 2020-10-17 19:22:19

perf_counter()应该测量进程实际花费的时间,就像您使用秒表一样。

process_time()会给出计算机在当前进程中花费的时间,有操作系统的计算机通常不会在任何给定的进程上花费100%的时间。此计数器不应计算cpu运行任何其他任务的时间。

大多数情况下,perf_counter可能更可取,但如果您想比较代码效率,process_time可能会很有用。

票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52222002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档