【问题标题】:Python: Throw ERROR on maxing out a time constantPython:在最大化时间常数时抛出错误
【发布时间】:2013-09-17 18:49:32
【问题描述】:

我看过这篇关于使用定时器的帖子:

Accurate timing of functions in python

虽然它确实有时间进行已知操作...但我需要一些稍微不同的东西。

我想要:

  1. 执行函数 + 启动计时器
  2. 允许函数运行
  3. 如果函数完成
  4. 如果函数完成 >=X 毫秒:错误“超出预期时间常数”

【问题讨论】:

    标签: python profiling


    【解决方案1】:

    您几乎可以将您的请求直接翻译成代码——只需添加一个“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")
    

    【讨论】:

    • 这行得通吗?根据我对 Timer 的了解... t = timeit.Timer() 语句只会返回“操作”完成后...因此它不会在“操作”期间发生错误,而是在“操作”执行后...对吗?
    • @delinquentme - 哦,我想明白你的意思了。与其简单地测量一个函数需要多长时间运行,不如在它超过某个阈值时立即停止它,对吧? questionanswer 是否更接近您的目标?
    • 上面的链接正是我需要的。谢谢!
    【解决方案2】:

    要抛出错误,请使用:

    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: 耗时过长

    【讨论】:

    • 就像下面的答案一样,这只会在 Timed 操作完成后引发异常。我需要一个正在运行的操作中的错误事件...一个正在运行的计时器,它不会等待正在计时的方法完成
    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    相关资源
    最近更新 更多