デコレータ | Pythonでなんか作ってみる

デコレータ

地味に一人か二人は見てくれているのだろうか?

この間、作った関数の処理時間を知りたくなって、もっとも簡単な方法は、単に時間を計ることだと、Python IAQに書いてあったので、デコレータにしてみた。


def timer(fn, *args):
"Time the application of fn to args. Return (result, seconds)."
import time
start = time.clock()
return fn(*args), time.clock() - start

>>>timer(max, range(1e6))
(999999, 0.4921875)


これを元に、timerを高階関数にする。

def timer(fn):
"Time the application of fn to args. Return (result, seconds)."
def __timer__(*args,**kwargs):
import time
start = time.clock()
fn(*args,**kwargs)
return time.clock() - start
return __timer__


こう使う

>>>timer(max)(range(1e6))
0.4921875

関数の方が実行時間しか返さなくなったのはご愛嬌だ。