微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决mpmath 在简单乘法中比十进制慢

我想知道为什么 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,我的机器是一台新的 T14s,带有 AMD7 和 32 GB RAM(不知道它是否有什么区别..)

解决方法

mpmath 是用 Python 编写的。 decimal 是用 C 编写的。C 扩展具有较少的解释器开销。就是这样。

请注意,即使您安装了 gmpy2,这也意味着 mpmath 将使用 gmpy2 整数而不是普通的 Python 整数。它不会自动 C 加速整个 mpmath 实现。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。