2012-06-12 34 views
2

我想測量我的一個小型Python代碼片段的執行時間,我想知道這樣做的最佳方式是什麼。避免在timeit.repeat()基準測試中設置昂貴的設置

理想情況下,我想運行某種設置(需要很長時間),然後運行一些測試代碼幾次,並獲得這些運行的最短時間。

timeit()似乎是合適的,但我不知道如何獲得最短的時間,而無需重新執行設置。小代碼片段演示了一個問題:

import timeit 

setup = 'a = 2.0' # expensive 
stmt = 'b = a**2' # also takes significantly longer than timer resolution 

# this executes setup and stmt 10 times and the minimum of these 10 
# runs is returned: 
timings1 = timeit.repeat(stmt = stmt, setup = setup, repeat = 10, number = 1) 

# this executes setup once and stmt 10 times but the overall time of 
# these 10 runs is returned (and I would like to have the minimum 
# of the 10 runs): 
timings2 = timeit.repeat(stmt = stmt, setup = setup, repeat = 1, number = 10) 
+2

您可以將安裝程序的結果存儲在變量中嗎? –

+0

由於涉及更復雜的數據類型(scipy.sparse.linalg.LinearOperator),我們無法將結果存儲在字符串中。 – andrenarchy

回答

1

您是否嘗試過使用datetime做你的時機嗎?

start = datetime.datetime.now() 
print datetime.datetime.now() - start #prints a datetime.timedelta object` 

這會給你時間的流逝,你可以控制它開始的地方很小的開銷。

編輯:這是一個人使用它也用於做一些時間的視頻,它似乎是獲得運行時間的最簡單方法。 http://www.youtube.com/watch?v=Iw9-GckD-gQ