2016-05-03 24 views
0

我試圖去理解它需要多長時間功能使用time.timer運行的運行時間,但我真的難倒如何實現它我想這會工作:使用定時器獲得funtion

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有人可以告訴我該怎麼做,我一直覺得它不是那麼辛苦,但我不知道如何。

回答

1

你可以使用一個裝飾器開始計時,運行真正的功能,它會自動結束後評價定時器:

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

'了time.time()'可能比'timeit不太精確.default_timer()'在Windows上。請參見[測量Python中的時間?](http://stackoverflow.com/a/25823885/4279) – jfs

2

你有很多現成的選項來計時你的功能 - 沒有必要在這裏重新發明輪子。

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