在Python中获取更精确的计时器

0 投票
2 回答
635 浏览
提问于 2025-04-16 14:22

给定这个示例代码:

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 模块,但不知道该怎么用,也不确定它是否能满足我的需求。

2 个回答

0

我还没有把这种方法和timeit进行比较,但有时候我会用日期时间的减法来快速测量时间。我回家后会做一些测试并进行比较。

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
2

使用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()中传入一个数字,来改变运行的次数。

撰写回答