【问题标题】:Timer shows negative time elapsed计时器显示负时间已过
【发布时间】:2013-07-21 06:08:20
【问题描述】:

我正在使用一个非常简单的代码来为 for 语句中的每个循环计时。它看起来像这样:

import time

for item in list_of_files:

    # Start timing this loop.
    start = time.clock()

    # Do a bunch of stuff.

    # Get time elapsed in seconds.
    elapsed = time.clock() - start

    # Get minutes and seconds.
    m, s = divmod(elapsed, 60)

    # Print result.
    print 'End of analysis for %s in %dm %02ds.\n'% (item, m, s)

这在大多数情况下会产生正确的输出,例如 9m 52s,但有时会出现大循环(需要一些时间),我会得到类似 -53m 17s 的负面结果。

我无法确定结果开始显示为负值的明确限制,但它显然只发生在经过时间 > 20 分钟的情况下,而不是 每个 花费 > 20 分钟的循环(即:不一致)。

我的代码中有什么东西可以对导致这种情况的每个循环进行计时吗?

添加

我使用 Spyder 作为我的 IDE。我比较了time.clock()time.time() 的表现,这就是我所看到的:

>>> st1, st2 = time.clock(), time.time()
>>> st1,st2
(507.65, 1374502193.357196)
>>> print time.clock()-st1, time.time()-st2
0.14 15.1921429634
>>> print time.clock()-st1, time.time()-st2
0.34 35.0087578297
>>> print time.clock()-st1, time.time()-st2
0.67 69.8715758324
>>> print time.clock()-st1, time.time()-st2
0.77 80.0557789803
>>> print time.clock()-st1, time.time()-st2
1.25 130.559605837
>>> print time.clock()-st1, time.time()-st2
3.02 309.845729828
>>> print time.clock()-st1, time.time()-st2
8.9 899.936934948

time.clock() 不应该以秒为单位返回经过的时间吗? time.time() 调用以秒为单位准确跟踪经过的时间(例如,最后一次调用是在 15 分钟后进行的,即 900 秒),但我不知道 time.clock() 在做什么。

【问题讨论】:

  • 好奇:您的bunch of stuff 中是否有任何线程? This is why I ask
  • 您是在 Windows 上工作还是在 Linux 上工作?
  • 你能找到具体的例子吗?
  • 我正在使用 Linux(实际上是基于 Ubuntu 12.04 的基本操作系统)@inspectorG4dget 给我几分钟时间检查一下,我不熟悉线程(这可能意味着我'不使用它)
  • 您是否尝试使用 time.time() 代替? docs.python.org/2/library/time.html

标签: python time


【解决方案1】:

我怀疑你遇到了某种溢出。

http://linux.die.net/man/3/clock

时钟的 linux 手册页建议时钟周期的返回值,因此,如果时钟恰好以高值开始并以低值停止,并且您的差是有符号的,您可能会得到一个负值表示经过的时间.

由于您要对持续数秒的事件进行计时,因此 time.time() 函数可能更适合您正在做的事情。

【讨论】:

    【解决方案2】:

    time.clock() 测量 Unix 系统上的 CPU 时间,而不是 wall 时间。有关底层系统调用的更多信息,请参阅http://pubs.opengroup.org/onlinepubs/007908799/xsh/clock.html(注意它说它可以包装的部分)。

    如果你想测量walltime,请使用time.time()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多