【问题标题】:using timer to get runtime of a funtion使用计时器获取函数的运行时间
【发布时间】:2016-05-03 06:45:30
【问题描述】:

我试图了解使用 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 的运行时间,有人能告诉我怎么做吗?我一直觉得这并不难,但我不知道怎么做。

【问题讨论】:

    标签: python time timer runtime execution


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      猜你喜欢
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多