概要
コードを書いていて気になったので, リストの積を計算する際にかかる時間を以下の3パターンで測ってみました.
- listをfor文で回す
- mathモジュールを使う
- numpyを使う
以下は実際に動かしたコード.
prod_time.py
import time
start = time.time()
A = [1] * 100000000
ans = 1
for a in A:
ans *= a
print("list loop:", time.time() - start)
import math
start = time.time()
ans = math.prod(A)
print("math.prod:", time.time() - start)
import numpy as np
start = time.time()
ans = np.prod(A)
print("numpy.prod:", time.time() - start)
出力結果は次のとおり.
list loop: 3.508364677429199
math.prod: 0.47490572929382324
numpy.prod: 2.398198127746582
結果
表にまとめると,
方法 | 計算時間 |
---|---|
for文 | 3.508364677429199 |
math.prod() | 0.47490572929382324 |
numpy.prod() | 2.398198127746582 |
どうやらmathモジュールを使う場合がかなり高速のようです!
※ちなみにAtcoderのpypy3ではバージョン的にmath.prod()は使えない (2023/4/24時点)