この記事では,pythonの関数の実行時間を計測する時間の方法をいくつか紹介する.
コードの実行した結果は,https://github.com/akitoshiblog/blogsite/blob/master/time_measurement/time_measurement.ipynb で見ることが出来る.
準備
今回時間を計測する関数は以下のものを用いる.
def wasteTime(num=5):
for n in range(num):
a = [i for i in range(10000)]
time.perf_counter()
time moduleの中でnano secondまでデフォルトでカバーしているのがこの関数のため,この記事が書かれた時点ではこれが時間計測を用いるのに望ましい.
最も基本的な方法は時間を計測する関数で,測定したい関数を挟む方法だ.
import time
st = time.perf_counter()
wasteTime()
en = time.perf_counter()
t = en - st
print(t)
Timer()
time.perf_counter()の基本形をクラス,context manager, decoratorの三つの方法どれでも使えるように拡張したのが,codetimingのTimerだ .詳細に関しては,参考文献を参照されたい.context manager, decoratorの仕様も勉強出来る.
インストールは, pip install codetiming
.使い方は,以下の通りである.
from codetiming import Timer
# クラス
t = Timer()
t.start()
wasteTime()
t.stop()
# context manager
with Timer():
wasteTime()
# decorator
@Timer()
def wasteTimeWrapped(num=5):
for n in range(num):
a = [i for i in range(10000)]
wasteTimeWrapped()
%timeit , %%timeit
jupyter notebook上で使える時間の関数の計測方法.
デフォルトだと,100回行った平均実行時間と標準偏差を出力してくれる.
%timeit は行単位で,%%timeit はセル単位で実行時間を計測する.
for i in range(30000):
a = i
%timeit wasteTime() # wasteTime() だけ測定.
%%timeit
for i in range(30000):
a = i
wasteTime()
cProfile
上記は単純に関数の実行時間を測定する方法であったが,cProfileは関数の中でどこが時間を取っているか確認出来るmoduleである.
import cProfile
cProfile.run('wasteTime(10)')
line_profiler
Robert Kernさんが作成した行ごとに実行時間を確認してくれるmodule.
どの関数のどの部分が時間が掛かってるかよく分かる.
インストールだけpipで上手く入らないので以下のようにしてインストールする.
from line_profiler import LineProfiler
git clone https://github.com/rkern/line_profiler.git
cd line_profiler
pip install cython
pip install .
以下に使用例を示す.
from line_profiler import LineProfiler
prof = LineProfiler()
prof.add_function(wasteTime)
prof.runcall(wasteTime,15,)
prof.print_stats(output_unit=1e-3)
参考文献
[1] Primer on Python Decorators, https://realpython.com/primer-on-python-decorators/
[2] Python Timer Functions: Three Ways to Monitor Your Code, https://realpython.com/python-timer/#a-python-timer-decorator
[3] The Ultimate Guide to Data Classes in Python 3.7, https://realpython.com/python-data-classes/
[4] Pythonのプロファイリング, https://qiita.com/meshidenn/items/4dbde22d1e7a13a255bb
[5] Pythonのline_profilerとmemory_profilerの紹介, https://qiita.com/aratana_tamutomo/items/aa3b723a3dd7a44e45d6
コメント