2011-03-24 74 views
0

更精确的计时器鉴于此示例代码:得到蟒蛇

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模块,但无法弄清楚如何使用它或它是否是我想要的。

+0

完整的代码是在这里http://pastie.org/1711210以防万一。 – Trufa 2011-03-25 16:52:19

回答

2

使用时间很简单。一个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()传递一个数字来运行它不同的次数。

+0

我会试试看,谢谢! – Trufa 2011-03-25 00:00:26

+0

我不明白'op =''''里面会发生什么 – Trufa 2011-03-25 00:04:04

+0

这就是你想要的所有代码。您传递给Timer的字符串不能在字符串外引用任何变量,因此您必须定义其中的所有内容。如果你给我用'x','userInput'和'epsilon'的值,我可以给你一个更完整的例子。 – Narcolei 2011-03-25 00:05:47

0

我还没有比较这种方式时间,但有时我使用日期时间扣除快速和脏的时间。当我回家并比较时,我会运行一些测试。

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 
+0

这是有益的感谢! – Trufa 2011-03-25 16:51:10