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)
您可以將安裝程序的結果存儲在變量中嗎? –
由於涉及更復雜的數據類型(scipy.sparse.linalg.LinearOperator),我們無法將結果存儲在字符串中。 – andrenarchy