【问题标题】:Working with time.process_time()使用 time.process_time()
【发布时间】:2018-05-15 22:06:36
【问题描述】:

我正在尝试计算排序功能需要多长时间,但我正在努力让time.process_time() 工作。

我目前的设置是:

start = time.process_time()
insertionsort(n)
end = time.process_time()

time = start-end

当我运行它时,我收到了这个错误:

'float' 对象没有属性 'process_time'

我该如何解决这个问题?我想使用time.process_time()

【问题讨论】:

  • 这就是问题所在。 time = start-end 不要将变量命名为与标准库相同的名称。

标签: python python-3.x attributeerror


【解决方案1】:

问题出在您未显示的部分代码中。我假设您在开始时导入了 time 模块:

import time

这会创建一个引用 time 模块的名称 time

但是稍后您创建了一个名为time 的变量来存储时差。此时名称time 引用了差异而不是模块。因此,当您之后尝试使用 time.process_time() 时,您会收到错误消息。

这个简单的 sn-p 说明了问题:

>>> import time
>>> time = -(time.process_time() - time.process_time())
>>> time.process_time()
AttributeError: 'float' object has no attribute 'process_time'

如果你坚持使用time.process_time(),最好的办法是重命名存储时差的变量:

measured_execution_time_insertionsort = end - start

但您也可以直接从time 模块导入process_time 函数:

from time import process_time

start = process_time()
insertionsort(n)
end = process_time()

time = end - start

这两种方法都避免了名称冲突。但是,如果您想测量执行时间,我建议您使用timeit 模块,它比time 模块更适合此类任务。

【讨论】:

  • 要获得肯定的时间答案,您需要将其设为time = end - start 而不是time = start - end
  • @ThomasS。是的,我最初是从问题中复制的。然而,有一个积极的结果似乎显然是正确的,所以我更新了答案。感谢您指出这一点。
  • 在运行import timetime = -(time.process_time() - time.process_time()) 后,我得到Traceback (most recent call last): File "<stdin>", line 1, in <module>。也许是因为我使用的是Python 2.7.12 (default, Mar 1 2021, 11:38:31)?如果我尝试做from time import process_time 我得到:Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name process_time
  • @user1271772 是的,这是因为您使用的是 Python 2。那里没有实现该功能。
猜你喜欢
  • 2014-11-05
  • 1970-01-01
  • 2019-02-12
  • 2021-02-04
  • 2019-05-01
  • 1970-01-01
  • 2016-03-23
  • 2015-09-08
  • 2020-12-19
相关资源
最近更新 更多