1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonの関数呼び出しをオブジェクトにぶち込んだら結構速くなった

Posted at

上司「pythonは関数呼び出しのコストそこそこかかるから、ループ深いところは予めオブジェクトに用意しておいたあげたほうが早くなるよ」
僕「はーい(そんなに変わるわけないっしょww)」

・・・と思って試してみました。

func_call_cost.py
import time
import datetime

TRIAL_NUM = 1000000

from_ts = datetime.datetime.fromtimestamp

def main():
    # unixtimeからdatetime作成する処理を100万回
    start = time.time()
    for i in range(TRIAL_NUM):
        datetime.datetime.fromtimestamp(i)
    print("time:{0}".format(time.time() - start))

    # 呼び出す関数を予めオブジェクトに用意しておく場合
    start = time.time()
    for i in range(TRIAL_NUM):
        from_ts(i)
    print("time:{0}".format(time.time() - start))


if __name__ == '__main__':
    main()

測定結果(10回平均)

普通に呼び出し オブジェクトに入れる
0.49sec 0.41sec

…まじか。高々100万回のループでそこまで変わるか。
導入するのもかなりイージーだしループ処理の深いところでは積極的に使っていきたい。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?