python计时器精度_在python中获得更精确的计时器
使用timeit很簡單。 Timer實例需要兩個字符串,第一個包含對time的操作,第二個包含在計時開始之前執行一次的設置操作。以下代碼應該可以工作,只需將變量值更改為您想要的任何值。
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()來運行它不同的次數。
總結
以上是生活随笔為你收集整理的python计时器精度_在python中获得更精确的计时器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回乡偶书的作者是谁啊?
- 下一篇: python读取文件r_python r