LoginSignup
0
0

More than 1 year has passed since last update.

【Python】リストの積の計算時間

Last updated at Posted at 2023-04-23

概要

コードを書いていて気になったので, リストの積を計算する際にかかる時間を以下の3パターンで測ってみました.

  1. listをfor文で回す
  2. mathモジュールを使う
  3. 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時点)

0
0
1

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