Decoratorを使えば、一種のベンチマークテスト(benchmark test)もできる。
ここでのベンチマークテストとは、その関数を実行するのに掛かる時間。
下記ファイルをbench.pyとして保存。
import time
import functools
def Timer(func):
@functools.wraps(func)
def Wrapper(*args, **kwargs):
stime = time.process_time()
ret = func(*args, **kwargs)
etime = time.process_time()
print('{0}: {1:,f}ms'.format(func.__name__, (etime - stime)*1000))
return ret
return Wrapper
@Timer
def Test():
print("Hello world")
Test()
こちらのページを参考にさせて頂きました。感謝。
pythonのデコレータを使ってお手軽ベンチマーク
こちらはPython(2)を元にしたコードなので少しPython3に手直ししています。
一番はPython3のtimeモジュールにはclockと言うattributeは無い事、printが関数になった事。
代わりのattribute、process_timeを使い、print()には括弧を付ける。
こちらを実行すると下記の様になり、通常の出力と共に、実行に掛かった時間が出る。
% python3 bench.py Hello world Test: 0.066000ms
Python decoratorの簡単な練習1でやった様にfor loopも測ってみる。
5個では少な過ぎるので、100まで(0〜99)の数字で下記のbenchfl.pyを作る。
import time
import functools
def Timer(func):
@functools.wraps(func)
def Wrapper(*args, **kwargs):
stime = time.process_time()
ret = func(*args, **kwargs)
etime = time.process_time()
print('{0}: {1:,f}ms'.format(func.__name__, (etime - stime)*1000))
return ret
return Wrapper
@Timer
def Test():
print("Hello world")
Test()
@Timer
def forloop():
for i in range(100):
print(i)
forloop()
出力は下記の通り、Hello world出力よりは少し時間が掛かったことが分かる。
% python3 benchfl.py Hello world Test: 0.193000ms 0 1 2 3 4 5 (中略) 96 97 98 99 forloop: 0.624000ms


コメント