在python中获得更精确的计时器
给定此示例代码:在python中获得更精确的计时器,python,timer,precision,milliseconds,Python,Timer,Precision,Milliseconds,给定此示例代码: 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很简
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很简单。计时器实例包含两个字符串,第一个包含要计时的操作,第二个包含在计时开始之前执行一次的设置操作。下面的代码应该可以工作,只需将变量值更改为您想要的值即可
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导入计时器
userInput=“0”
而不是userInput.isdigit()或int(userInput)epsilon):
x=0.5*(x+(用户输入/x))
计数=计数+1
打印(“La raíz de”,用户输入,“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
我无法理解
op=''
中的内容,这将是所有您想要计时的代码。传递给计时器的字符串不能引用字符串之外的任何变量,因此必须定义其中的所有内容。如果你给我你用于x
、userInput
和epsilon
的值,我可以给你一个更完整的例子。@Narcolei:所以如果我想计时,while循环ti应该在之间。
?我编辑了答案,使它更完整。现在有意义了吗?我可以有代码:)在这个特殊的cas中,您会怎么做,抱歉打扰了!我似乎不知道什么是字符串。完整的代码在这里以防万一。