首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在简单乘法中,mpmath比十进制慢

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

Stack Overflow用户
提问于 2021-05-21 01:39:29
回答 1查看 70关注 0票数 1

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

代码语言:javascript
复制
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")

输出:

代码语言:javascript
复制
Using Decimal: 0.3805640869977651
Using mpmath: 2.961118871004146
You are using gmpy2

差值大约是8倍。

我使用的是Python3.8,我的机器是一个带有AMD7和32 GB内存的新T14s (不知道这是否有什么不同..)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-11 19:33:07

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

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67625448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档