2011-08-08 138 views
2

我有一個關於python中timeit模塊的問題,它用於確定一段代碼執行所花費的時間。關於Python中timeit模塊的問題

t = timeit.Timer("foo","from __main__ import foo") 
str(t.timeit(1000)) 

在上面的代碼中參數1000是什麼意思?

回答

1

作爲documented,數字表示timeit執行指定程序的次數。

由於高速緩存造成的前幾次執行速度可能會明顯變慢,而且各個執行時間可能會有很大差異,所以更多的時間運行(即更高的值)將產生更精確的結果,但也需要更長的時間。

4

documentation

Timer.timeit([number=1000000]) 

時間主語句的執行number。這會執行一次 設置語句,然後返回主語句多次執行 所需的時間,以秒爲單位測量爲浮點數。 參數是循環次數,默認爲 百萬。主語句,設置語句和要使用的定時器函數被傳遞給構造函數。

1

在教人以漁的精神,就問我的Python:

>>> import timeit 
>>> t=timeit.Timer() 
>>> help(t.timeit) 
Help on method timeit in module timeit: 

timeit(self, number=1000000) method of timeit.Timer instance 
    Time 'number' executions of the main statement. 

    To be precise, this executes the setup statement once, and 
    then returns the time it takes to execute the main statement 
    a number of times, as a float measured in seconds. The 
    argument is the number of times through the loop, defaulting 
    to one million. The main statement, the setup statement and 
    the timer function to be used are passed to the constructor.