【问题标题】:Python: Significant difference betweek time.time() vs. time.clock()?Python:betweek time.time() 与 time.clock() 的显着差异?
【发布时间】:2017-04-10 15:27:43
【问题描述】:

我正在尝试测试一个 http 请求处理代码块在我的烧瓶控制器中需要多长时间,这是我使用的示例代码:

cancelled = []
t0 = time.time()
t1 = time.clock()   
users = requests.get('https://www.example.com/users/')   
for i in users.json():
    user = requests.get('https://www.example.com/user/%s' % i['id]').json()
    if user['status'] == 'Cancelled':
        cancelled.append(user)
t2 = time.clock()
t3 = time.time()
print t2 - t1
print t3 - t0

这里是输出:

2.712326
76.424875021

time.time() 函数的第二个输出与显示结果所用的实际秒数相匹配,所以我不确定为什么 time.clock() 的值如此之小?

编辑:我的系统是 OSX 和 python 2.7,我的问题是,如果 time.time() 反映用户体验/等待的实际时间,为什么 time.clock() 通常被认为“更好”?

【问题讨论】:

  • 如果你在 unix 上,time.clock() 是处理器时间,time.time() 是自纪元以来的秒数
  • 什么操作系统? time.clock 返回“当前处理器时间”。文档说“精度,实际上是“处理器时间”含义的定义,取决于同名 C 函数的精度”
  • 如果 time.time() 反映了用户体验/等待的实际时间,为什么 time.clock() 通常被认为“更好”?

标签: python performance unit-testing time


【解决方案1】:

请注意,从 Python 3.3 开始,time.clock 现在是 deprecated,因为行为取决于平台。文档建议使用time.process_timetime.perf_counter 来衡量性能。

否则我会推荐使用timeit 模块(特别是因为这可以让您更好地控制测试环境)

【讨论】:

    猜你喜欢
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2013-01-19
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多