0

I am trying to understand how long it takes for a function to run using time.timer, but im really stumped on how to implement it I thought this would work:

def breadth_first_tree_search(problem):
  "Search the shallowest nodes in the search tree first."
  t1 = timeit.Timer(lambda: problem)
  n = 1
  secs = t1.timeit(number = n)
  print ("\n%d times took %8f seconds" % (n,secs))
  return tree_search(problem, FIFOQueue())

but then I realized its timing the wrong thing. I need it to check the runtime of breadth_first_tree_search can some one tell me how to do thi I keep getting the feeling that it isnt that hard but I cant figure out how.

2 Answers2

2

You have a lot of readily available options for timing your functions -- there's no need to reinvent the wheel here.

Using ipython : %timeit breadth_first_tree_search(problem)

Using Profile: https://docs.python.org/3/library/profile.html

If you really want to use timeit.Timer, follow the example in the docs.

timeit.Timer(stmt = lambda : breath_first_tree_search(problem)).timeit()
Thtu
  • 1,992
  • 15
  • 21
1

You could use a decorator to start the timer, run the real function and evaluate the timer after it finished automatically:

# write a decorator function taking the function to decorate as only parameter:
def timer_decorator(func):

    # define an inner function as wrapper with a flexible signature as your target function:
    def wrapper(*args, **kwargs):

        # set up timing:
        start_time = time.time()

        # call the wrapped function (passed as 'func' argument):
        return_value = func(*args, **kwargs)

        # check the timer and evaluate the time span:
        end_time = time.time()
        time_span = end_time - start_time
        print("Function '{}' took {:.3}s to run.".format(func.__name__, time_span))

        # return the decorated function's return value:
        return return_value

    # return the constructed wrapper function (don't call it --> no brackets "()" !):
    return wrapper

# Decorate your original function with your decorator:
@timer_decorator
def breadth_first_tree_search(problem):
    "Search the shallowest nodes in the search tree first."
    return tree_search(problem, FIFOQueue())

# Call your decorated function just like a normal function without any decoration:
breadth_first_tree_search("however you specify a problem...")
Byte Commander
  • 6,506
  • 6
  • 44
  • 71
  • 1
    `time.time()` might be less precise than `timeit.default_timer()` on Windows. See [Measure time elapsed in Python?](http://stackoverflow.com/a/25823885/4279) – jfs May 03 '16 at 19:07