为什么Mac OS X上的Python time.time()和time.clock()有差异? [英] Why are there differences in Python time.time() and time.clock() on Mac OS X?

查看:181
本文介绍了为什么Mac OS X上的Python time.time()和time.clock()有差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Mac OS X 10.8,并且time.clock()出现异常行为,一些在线消息人士说,我应该更喜欢time.time()来计时我的代码.例如:

I'm running Mac OS X 10.8 and get strange behavior for time.clock(), which some online sources say I should prefer over time.time() for timing my code. For example:

import time    
t0clock = time.clock()
t0time = time.time()
time.sleep(5)
t1clock = time.clock()
t1time = time.time()
print t1clock - t0clock
print t1time - t0time

0.00330099999999 <-- from time.clock(), clearly incorrect
5.00392889977    <-- from time.time(), correct

为什么会这样?我应该只使用time.time()进行可靠的估算吗?

Why is this happening? Should I just use time.time() for reliable estimates?

推荐答案

来自 time.clock :

在Unix上,以秒为单位返回当前处理器时间,以浮点数表示.精度(实际上是处理器时间"的含义的确切定义)取决于同名C函数的精度,但是无论如何,这是用于基准化Python或计时算法的函数.

来自 time.time 上的文档:

From the docs on time.time:

返回自纪元以来的时间(以秒为单位)为浮点数.请注意,即使始终将时间作为浮点数返回,但并非所有系统都提供比1秒更好的精度的时间.虽然此函数通常返回非递减值,但如果两次调用之间的系统时钟都已设置回去,则它可以返回比上一个调用更低的值.

Return the time in seconds since the epoch as a floating point number. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

time.time()以秒为单位,time.clock()测量当前进程已使用的CPU时间.但是在Windows上,这是不同的,因为clock()也可以测量秒.

time.time() measures in seconds, time.clock() measures the amount of CPU time that has been used by the current process. But on windows, this is different as clock() also measures seconds.

这是一个类似的问题

这篇关于为什么Mac OS X上的Python time.time()和time.clock()有差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆