【发布时间】:2021-01-05 13:08:20
【问题描述】:
我在 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怎么这么慢?
【问题讨论】:
-
您确定
mpmath使用的是gmpy2?文档说mpmath'将使用gmpy(如果有),而没有提及gmpy2(可能只是一个疏忽,一个项目是从另一个项目中产生的)。我不知道他们为跟上 gmpy/gmpy2 版本付出了多少努力,而且他们可能无法与gmpy2一起使用,因为它可能在 2.0 版本中发生了一些重大变化。 -
能否请您检查并粘贴 python、gmpy2、、mpmath 的版本。还请检查所有 C 库,gmpy2 depends 是否已正确编译和安装。对于两个库来说,单次操作的结果非常很慢,我想问题在于 C 库在后台运行。
-
抱歉,我没有注意到版本已经存在。我仍然认为你应该检查例如如果
libmpfr和libmpfr-dev(假设它的 debian 或类似的,或适用于您的操作系统的等效)已正确安装并正常工作 -
@ShadowRanger
mpmath.libmp.BACKEND说gmpy即使 gmpy 没有安装 - mpmath 也将 try to importgmpy2首先。 -
mpmath将尝试使用gmpy2或gmpy来替换Python 的内置整数类型。mpmath不会调用gmpy2/gmpy中的mpfr或mpc相关函数。稍后我会详细介绍。
标签: python exponentiation mpmath gmpy mpc