Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

Python でプログラム実行にかかる時間を計測する(timeitモジュール)

 

こんにちは、鯨井貴博@opensourcetechです。

 

今回は、Pythonでプログラム実行処理時間を計測する timeitモジュールを使うメモです。

 27.5. timeit — 小さなコード断片の実行時間計測 — Python 3.6.5 ドキュメント

 

timeitモジュールの使用方法

bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def testranger():・・・適当な関数の定義
...           def range():
...                  x = 7
...                  print(x)
...
>>> import timeit・・・timeitモジュールのインポート
>>> print(timeit.timeit(testranger))・・・処理時間の出力
0.141465902328
>>> print(timeit.timeit(testranger))
0.145117044449
>>> print(timeit.timeit(testranger))
0.145160913467
>>> print(timeit.timeit(testranger))
0.145545005798
>>> print(timeit.timeit(testranger))
0.145556926727
>>> print(timeit.timeit(testranger))
0.146238088608
>>> print(timeit.timeit(testranger))
0.145891904831

 

 なお、実行するマシンの状況等によって処理時間が前後するので、

複数回実行して平均をとるのがちょうどいいのかなと思います。

 

 

 

 

 

www.slideshare.net

github.com

www.facebook.com

twitter.com

www.instagram.com

 

 

にほんブログ村 IT技術ブログ Linuxへ
Linux

にほんブログ村 IT技術ブログ オープンソースへ
オープンソース

 

Opensourcetech by Takahiro Kujirai