鉴于此示例代码:
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
模块,但不知道如何使用它或者它是否是我想要的。
鉴于此示例代码:
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
模块,但不知道如何使用它或者它是否是我想要的。
使用 timeit 很简单。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")
这将默认运行您的代码一百万次,并以秒为单位返回运行的总时间。您可以通过将数字传递给timeit()
.
我没有将这种方式与 timeit 进行比较,但有时我会使用 datetime 减法来进行快速而肮脏的计时。我回家后会进行一些测试并进行比较。
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