我想知道为什么 mpmath 在为相同的精度设置执行相同的操作时比十进制慢得多。
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,我的机器是带有 AMD7 和 32 GB RAM 的新 T14(不知道它是否有任何区别..)