【问题标题】:Get a more precise timer in python在python中获得更精确的计时器
【发布时间】:2011-03-24 23:45:21
【问题描述】:

鉴于此示例代码:

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 模块,但不知道如何使用它或它是否是我想要的。

【问题讨论】:

标签: python timer precision milliseconds


【解决方案1】:

使用 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() 来运行它不同的次数。

【讨论】:

  • 我看不懂op = '''里面的内容
  • 这将是您想要计时的所有代码。您传递给 Timer 的字符串不能引用字符串之外的任何变量,因此您必须定义其中的所有内容。如果你给我你用于xuserInputepsilon的值,我可以给你一个更完整的例子。
  • @Narcolei: 所以如果我想计时这个while循环ti应该在'之间?
  • 我编辑了答案以使其更完整。现在有意义吗?
  • 我有代码 :) pastie.org/1711210 在这种特殊情况下你会怎么做,抱歉打扰!我似乎无法弄清楚什么是字符串。
【解决方案2】:

我没有将这种方式与 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多