我在 gmpy2 中使用复数并注意到它很慢。我缩小了求幂运算符的范围。起初我以为这只是因为它很复杂。但后来我将它与使用gmpy2 的 mpmath 进行了比较,发现速度要快得多:
# tested using gmpy2 2.0.8, mpmath 1.1.0, python 3.8.5
>>> import timeit
>>> setup = '''
import gmpy2 as gm
import mpmath
a1 = gm.mpc(-12.5, 34.125)
a2 = gm.mpc(17, -45.875)
b1 = mpmath.mpc(-12.5, 34.125)
b2 = mpmath.mpc(17, -45.875)
'''
# using gmpy2
>>> timeit.timeit('a1 ** a2', setup)
87.13848301399992
>>> timeit.timeit('a1 ** 2', setup)
40.478690218
>>> timeit.timeit('pow(a1, 2)', setup)
40.70392542999991
# using mpmath
>>> timeit.timeit('b1 ** b2', setup)
51.799312732999965
>>> timeit.timeit('b1 ** 2', setup)
4.239320562999978
>>> timeit.timeit('pow(b1, 2)', setup)
4.293315565000057
# multiplication comparison
>>> timeit.timeit('a1 * a1', setup)
0.9900801109999975 # gmpy2
>>> timeit.timeit('b1 * b1', setup)
4.711916033999955 # mpmath
纯复数幂运算非常慢,但 mpmath 仍然比 gmpy2 快 40% 左右。由于 mpmath 是 Python,我认为它会慢得多,但事实显然并非如此。gmpy2 怎么这么慢?
饮歌长啸
相关分类