LoginSignup
1
4

More than 5 years have passed since last update.

【Python】関数呼び出しのコストを計測してみた

Last updated at Posted at 2018-08-22

関数呼び出しのコストがどのくらいかかるかが気になったので。

関数の準備
# ループ用のリスト
n = [0] * 10000000

# ループで毎回呼び出される関数
def test1():
    1 + 1

# 一度だけ呼び出されて中でループする関数
def test2():
    for _ in n:
        1 + 1

まずはループする度に関数を呼び出す場合。
実行する度に時間が異なったのでとりあえず3回実行。

test1(ipython上で実行)
In [57]: %time for _ in n: test1()
Wall time: 1.42 s

In [58]: %time for _ in n: test1()
Wall time: 1.12 s

In [59]: %time for _ in n: test1()
Wall time: 1.18 s

次に一度だけ呼び出されて,関数内で同じ回数だけループする場合。
同様に3回実施。

test2(ipython上で実行)
In [60]: %time test2()
Wall time: 362 ms

In [61]: %time test2()
Wall time: 176 ms

In [62]: %time test2()
Wall time: 225 ms

このケースだとざっくり3倍以上は違うようですね。
ループ等で何度も関数を呼び出している場合は,パフォーマンス向上のためにやり方を工夫する手もありそうです。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4