1
2

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 5 years have passed since last update.

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

Last updated at Posted at 2017-09-01

追記

@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の積を計算するのに最も速いのはなにかというお題です.

標準のライブラリで

検索するとreduceを使うのがよくヒットします.

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

本命です.sumの掛け算バージョンであるsympy.prodがあります.

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倍以上速い!

1
2
3

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?