【发布时间】:2013-09-17 18:49:32
【问题描述】:
我看过这篇关于使用定时器的帖子:
Accurate timing of functions in python
虽然它确实有时间进行已知操作...但我需要一些稍微不同的东西。
我想要:
- 执行函数 + 启动计时器
- 允许函数运行
- 如果函数完成
- 如果函数完成 >=X 毫秒:错误“超出预期时间常数”
【问题讨论】:
我看过这篇关于使用定时器的帖子:
Accurate timing of functions in python
虽然它确实有时间进行已知操作...但我需要一些稍微不同的东西。
我想要:
【问题讨论】:
您几乎可以将您的请求直接翻译成代码——只需添加一个“if”语句,然后抛出一个异常:
import timeit
def test(operation, setup, threshold):
# Add any kind of timing setup here.
t = timeit.Timer(operation, setup=setup)
# Note: t.timeit(number=1) returns the time in seconds, not milliseconds
if t.timeit() > threshold:
raise Exception("ERROR: expected time constant exceeded")
要抛出错误,请使用:
raise Exception("my message")
(适用于 Python 2.7,我不确定 3)
所以在你的函数中:
if time >= expected: raise Exception("took too long!")
你也可以有自己的错误类:
class TooLongError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
raise TooLongError("took too long")
生产:
TooLongError: 耗时过长
【讨论】: