2011-03-24 99 views
0

更精確的計時器鑑於此示例代碼:得到蟒蛇

start = time.clock() 

while (abs(x**2 - userInput) > epsilon): 

    x = 0.5 * (x + (userInput/x)) 
    count = count+1 

end = time.clock() 

print(end-start) 

而且考慮到這一操作,需要一點點時間,我怎樣才能得到更精確的計時器?

我看過timeit模塊,但無法弄清楚如何使用它或它是否是我想要的。

+0

完整的代碼是在這裏http://pastie.org/1711210以防萬一。 – Trufa 2011-03-25 16:52:19

回答

2

使用時間很簡單。一個Timer實例需要兩個字符串,第一個包含時間操作,第二個包含設置操作,在定時開始前執行一次。下面的代碼應該可以工作,只需將變量值更改爲任何你想要的。

import math 
import time 
from timeit import Timer 

userInput = "0" 

while not userInput.isdigit() or int(userInput) <= 0: 

    userInput = input("Calcular la raiz de: ") #Get input from user (userInput) 

userInput = int(userInput) 

epsilon = 0.000001 
x=1 
count=0 

setup = 'from __main__ import userInput, epsilon, x, count' 

operations = ''' 
x = 1 
count = 0 
while (abs(x**2 - userInput) > epsilon): 

    x = 0.5 * (x + (userInput/x)) 
    count = count+1 
''' 

print('The operations took %.4f microseconds.' % Timer(operations, setup).timeit(1)) 

#run the operations again to get the x and count values 
x = 1 
count = 0 
while (abs(x**2 - userInput) > epsilon): 

    x = 0.5 * (x + (userInput/x)) 
    count = count+1 
print("La raíz de", userInput, "es:",x,"implicó",count,"intentos") 

這會將您的代碼默認運行100萬次,並返回運行所花費的總時間(秒)。您可以通過向timeit()傳遞一個數字來運行它不同的次數。

+0

我會試試看,謝謝! – Trufa 2011-03-25 00:00:26

+0

我不明白'op =''''裏面會發生什麼 – Trufa 2011-03-25 00:04:04

+0

這就是你想要的所有代碼。您傳遞給Timer的字符串不能在字符串外引用任何變量,因此您必須定義其中的所有內容。如果你給我用'x','userInput'和'epsilon'的值,我可以給你一個更完整的例子。 – Narcolei 2011-03-25 00:05:47

0

我還沒有比較這種方式時間,但有時我使用日期時間扣除快速和髒的時間。當我回家並比較時,我會運行一些測試。

import datetime 

x = 1 
count = 0 
userInput = 1 
epsilon = 1 

start = datetime.datetime.now() 

while (abs(x**2 - userInput) > epsilon): 
    x = 0.5 * (x + (userInput/x)) 
    count = count+1 

print datetime.datetime.now() - start, "s" 

結果:

0:00:00.000011 s 
+0

這是有益的感謝! – Trufa 2011-03-25 16:51:10