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

using timer to get runtime of a funtion

我试图了解使用 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,请按照示例in the docs

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