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モジュールを見てきましたが、それを使用する方法や、それが私が望むものかどうかを理解できませんでした.

4

2 に答える 2

2

timeit の使用は簡単です。Timer インスタンスは 2 つの文字列を受け取ります。最初の文字列には時間に対する操作が含まれ、2 番目の文字列には計時が始まる前に 1 回実行されるセットアップ操作が含まれます。次のコードは機能するはずです。変数の値を必要なものに変更するだけです。

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()

于 2011-03-24T23:57:38.763 に答える
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
于 2011-03-25T00:51:01.903 に答える