sympy.Mul is much faster than sympy.prod

Postscript

[Comment] from @matsulib (http://qiita.com/HigashinoSola/items/7514035a5dbaadbc5762#comment-84c5a9c6da4f027361ae). Sympy.Mul is fast because the cache is enabled by default.


Randomly create 100 integers between 1 and 100.

import numpy as np
nums = [int(i) for i in np.random.randint(1, 100, 100)] #numpy.set int64 to int

The subject is what is the fastest way to calculate the product of nums.

With a standard library

When searching, it is often a hit to use 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)

It became faster by using ʻoperator.mul`.

numpy

I'm not sure, but it wasn't calculated correctly due to overflow.

np.prod(nums)
0

sympy

It is a favorite. There is a multiplied version of 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)

However, in fact, the barrier is that sympy.Mul is faster.

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

What is the reason for the existence of sypmy.prod ...

Conclusion

sympy.Mul (* nums) is more than twice as fast as sympy.prod (nums)!

Recommended Posts

sympy.Mul is much faster than sympy.prod
@ Is faster than dot
[Small story] In Python, i = i + 1 is slightly faster than i + = 1.
Python release cycle is faster!
[Python competition professional memo] LRU cache is faster than programmatic memoization