[解決!Python]timeモジュールで実行時間を計測するには:解決!Python
timeモジュールのtime関数やperf_counter関数を使って、特定の処理の実行にかかった時間を計測する方法を紹介する。
# 基本型
import time
start = time.time() # 現在時刻(処理開始前)を取得
# 実行したい処理を記述
end = time.time() # 現在時刻(処理完了後)を取得
time_diff = end - start # 処理完了後の時刻から処理開始前の時刻を減算する
print(time_diff) # 処理にかかった時間データを使用
def fact(x):
result = 1
if x == 0 or x == 1:
return result # 0!と1!の値は1
for n in range(1, x+1):
result *= n
return result
start = time.time()
for n in range(10000):
result = fact(1000)
end = time.time()
time_diff = end - start
print(time_diff)
# time.perf_counter関数を使う
start = time.perf_counter()
for n in range(10000):
result = fact(1000)
end = time.perf_counter()
time_diff = end - start
print(time_diff)
# 処理時間を計測する関数を定義
def get_time_diff(func, *args, time_func=time.time, count=1000):
result = None
start = time_func()
for _ in range(count):
result = func(*args)
end = time_func()
time_diff = end - start
return time_diff, result
time_diff, result = get_time_diff(fact, 1000)
timeモジュールのtime関数/perf_counter関数を使った実行時間の計測
Pythonのtimeモジュールにはtime関数やperf_counter関数がある。これらの関数を使うと、特定の処理にかかった時間を計測できる。
その手順はおおよそ次のようになる。
- 処理を始める直前でtime.time関数やtime.perf_counter関数を呼び出して、処理開始時点の値を取得する
- 実行時間を計測したい処理を記述する
- 処理が終わった時点でtime.time関数やtime.perf_counter関数をもう一度呼び出して、処理終了時点の値を取得する
- 処理終了時点の値から処理開始時点の値を減算することで、処理にかかった時間が分かる
これをコードにすると次のようになる。
import time
start = time.time() # 現在時刻(処理開始前)を取得
# 実行したい処理を記述
end = time.time() # 現在時刻(処理完了後)を取得
time_diff = end - start # 処理完了後の時刻から処理開始前の時刻を減算する
print(time_diff) # 処理にかかった時間データを使用
Copyright© Digital Advantage Corp. All Rights Reserved.