使用时间很简单。一个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