使用定时器获取函数的运行时间



我试图了解一个函数使用time.timer运行需要多长时间,但我真的很难理解如何实现它,我认为这会起作用:

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())

但后来我意识到它的时机不对。我需要它来检查breadth_first_tree_search的运行时,有人能告诉我怎么做吗?我一直觉得这没那么难,但我不知道怎么做。

您有很多现成的选项来定时您的函数——这里没有必要重新发明轮子。

使用ipython:%timeit breadth_first_tree_search(problem)

使用配置文件:https://docs.python.org/3/library/profile.html

如果您真的想使用timeit.Timer,请按照文档中的示例进行操作。

timeit.Timer(stmt = lambda : breath_first_tree_search(problem)).timeit()

您可以使用装饰器来启动计时器,运行真正的函数,并在计时器自动完成后对其进行评估:

# 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...")

最新更新