timeit の使用は簡単です。Timer インスタンスは 2 つの文字列を受け取ります。最初の文字列には時間に対する操作が含まれ、2 番目の文字列には計時が始まる前に 1 回実行されるセットアップ操作が含まれます。次のコードは機能するはずです。変数の値を必要なものに変更するだけです。
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()
。