使用時間很簡單。一個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()
傳遞一個數字來運行它不同的次數。
完整的代碼是在這裏http://pastie.org/1711210以防萬一。 – Trufa 2011-03-25 16:52:19