0

I've seen this post on using Timer:

Accurate timing of functions in python

And while it does get the time for a known operation... I need something slightly different.

I want:

  1. execute a function + start a timer
  2. allow function to run
  3. if function completes < X milliseconds: no error
  4. if function completes >=X milliseconds: ERROR "expected time constant exceeded"
Community
  • 1
  • 1
carl crott
  • 753
  • 1
  • 9
  • 21

2 Answers2

2

You can translate your request almost directly into code -- simply add an "if" statement, and throw an exception:

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")
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • Would this work? From what I understand about Timer ... the t = timeit.Timer() statement will only return post completion of "operation" ... thus it won't event an error DURING "operation" but instead post execution of "operation" ... right? – carl crott Sep 18 '13 at 22:12
  • 2
    @delinquentme - oh, I think see what you mean. Rather then simply measuring how long a function takes to run, you want to stop it immediately when it crosses some threshold, right? Is this [question](http://stackoverflow.com/a/601168/646543) and [answer](http://stackoverflow.com/a/601168/646543) closer to what you're looking for? – Michael0x2a Sep 18 '13 at 22:42
  • The links above covered exactly what I needed. Thanks! – carl crott Sep 22 '13 at 23:47
0

To throw an error use:

raise Exception("my message")

(works at Python 2.7, I'm not sure about 3)

So in your function:

if time >= expected: raise Exception("took too long!")

You can also have your own error class:

class TooLongError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

raise TooLongError("took too long")

Produces:

TooLongError: took too long

Nacib Neme
  • 859
  • 1
  • 17
  • 28
  • Like the answer below, this would raise an exception only after completion of the Timed operation. I need an error EVENT within the operation being run... A running timer, which doesn't wait for the completion of the method being timed – carl crott Sep 18 '13 at 22:16