Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@HigashinoSola

sympy.prodよりsympy.Mulの方がかなり速い

More than 3 years have passed since last update.

追記

@matsulib 様よりコメントいただきました．sympy.Mulはデフォルトでキャッシュが有効になっているから速いとのことです．

1以上100未満の整数100個をランダムに作ります．

``````import numpy as np
nums = [int(i) for i in np.random.randint(1, 100, 100)] #numpy.int64をintにしておく
``````

`nums`の積を計算するのに最も速いのはなにかというお題です．

標準のライブラリで

``````from functools import reduce
from operator import mul
``````
``````%timeit reduce(lambda x, y: x*y, nums)
``````
``````11.7 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
``````
``````%timeit reduce(mul, nums)
``````
``````6.71 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
``````

`operator.mul` を用いると速くなりました．

numpy

よく分かりませんが，オーバーフローで正しく計算されませんでした．

``````np.prod(nums)
``````
``````0
``````

sympy

``````import sympy
``````
``````%timeit sympy.prod(nums)
``````
``````7.1 µs ± 50.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
``````

しかし，実は`sympy.Mul` の方が速いという結界に．

``````%timeit sympy.Mul(*nums)
``````
``````2.96 µs ± 39.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
``````

`sypmy.prod`の存在理由とはいったい……

結論

`sympy.prod(nums)` より `sympy.Mul(*nums)` の方が2倍以上速い！

2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
EPUB3 + MathML に興味あり．Pythonと数学が相性良さげでよく使ってます．