mpmath在简单乘法中比十进制慢



我想知道为什么在对相同精度设置执行相同操作时,mpmath比decimal慢得多。

from decimal import *
from mpmath import *
import timeit
from decimal import Decimal as dc
from mpmath import mpf
import sys
# Set the same precision 
getcontext().prec = 15
mp.dps = 15
# A random function which does multiplication using mpmath
def mpf_test():
a = mpf('2202020202002020.21212')
b = mpf('3202020202002020.21212')
c = mpf(0)
for _ in range(10000):
c += (a*b) / (a*b)
# The same function which does the multiplication using decimal
def decimal_test():
a = dc('2202020202002020.21212')
b = dc('3202020202002020.21212')
c = dc(0.0)
for _ in range(10000):
c += (a*b) / (a*b)

# Print results
print(F"Using Decimal: {timeit.timeit(stmt=decimal_test, number=100)}")
print(F"Using mpmath: {timeit.timeit(stmt=mpf_test, number=100)}")
# Check if gmpy2 is used in mpmath
if 'gmpy2' in sys.modules:
print(F"You are using gmpy2")

输出:

Using Decimal: 0.3805640869977651
Using mpmath: 2.961118871004146
You are using gmpy2

差异大约是8倍。

我使用的是Python3.8,我的机器是一台新的T14,带有AMD7和32GB RAM(不知道这是否有什么不同…(

mpmath是用Python编写的。decimal是用C.C编写的。C扩展具有较少的解释器开销。仅此而已。

请注意,即使安装了gmpy2,这也意味着mpmath将在后台使用gmpy2整数,而不是常规的Python int。它不会自动C加速整个mpmath的实现。

最新更新