僕とコードとブルーハワイ

omega (@equal_001) の日記

メモ: Pythonのパフォーマンスチューニング cProfile

=================
環境:MacOS X 10.4

Python -V:3.4.2
=================

最近パフォーマンスチューニングをすることが多いのでメモ。

ドキュメント: 27.4. Python プロファイラ — Python 3.4.3 ドキュメント



良い例が思いつかなくてアレだけど、とりあえず呼び出し回数と実行時間の違いがわかるものを書いた。
100万回join_textを呼び出して、渡ってきた数字が偶数ならBlue、奇数ならRedのNo.として返してひたすらtext変数にstrでつなげるやつ。

 1  def main():
 2     text = ''
 3     num_list = range(1000000)
 4     for num in num_list:
 5         text += join_text(num)
 6
 7  def join_text(num):
 8      if num % 2 == 0:
 9          return "Blue_No.{}".format(str(num))
 10     else:
 11         return "Red_No.{}".format(str(num))
 12 
 13  if __name__ == '__main__':
 14     import cProfile
 15     cProfile.runctx("main()", globals(), locals())

実行結果

         2000004 function calls in 1.396 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    1.396    1.396 <string>:1(<module>)
        1    0.414    0.414    1.395    1.395 profile_test.py:1(main)
  1000000    0.646    0.000    0.981    0.000 profile_test.py:7(join_text)
        1    0.000    0.000    1.396    1.396 {built-in method exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
  1000000    0.335    0.000    0.335    0.000 {method 'format' of 'str' objects}


なんかもっと複雑なやつにcProfile通してみると冗長な書き方とかいっぱいでてきて面白い。