【问题标题】:How to use JIT in python with mpmath / gmpy effectively?如何在 python 中有效地使用 JIT 和 mpmath / gmpy?
【发布时间】:2018-02-28 16:50:51
【问题描述】:

这是我第一次尝试将 JIT 用于 python,这是我想要加快速度的用例。我读了一些关于 numba 的内容,它看起来很简单,但是下面的代码没有提供任何加速。请原谅我可能犯的任何明显错误。

我也尝试按照 cython 的基本教程的建议进行操作,但在时间上也没有区别。 http://docs.cython.org/src/tutorial/cython_tutorial.html

我猜我必须做一些类似声明变量的事情?使用其他库?只为所有内容使用 for 循环?如有任何指导或示例,我将不胜感激。

例如,我从上一个问题Elementwise operations in mpmath slow compared to numpy and its solution 中知道,使用 gmpy 代替 mpmath 明显更快。

import numpy as np
from scipy.special import eval_genlaguerre
from sympy import mpmath as mp
from sympy.mpmath import laguerre as genlag2
import collections

from numba import jit

import time

def len2(x):
    return len(x) if isinstance(x, collections.Sized) else 1

@jit # <-- removing this doesn't change the output time if anything it's slower with this
def laguerre(a, b, x):
    fun = np.vectorize(genlag2)
    return fun(a, b, x)

def f1( a, b, c ):

    t       = time.time()
    M       = np.ones( [ len2(a), len2(b), len2(c) ] )
    A, B, C = np.meshgrid( a, b, c, indexing = 'ij' )
    temp    = laguerre(A, B, C)
    M      *= temp
    print 'part1:      ', time.time() - t
    t       = time.time()

    A, B    = np.meshgrid( a, b, indexing= 'ij' )
    temp    = np.array( [[ mp.fac(x1)/mp.fac(y1) for x1,y1 in zip(x2,y2)] for x2,y2 in zip(A, B)] )
    temp    = np.reshape( temp, [ len(a), len(b), 1 ] )
    temp    = np.repeat(  temp, len(c), axis = 2 )
    print 'part2 so far:', time.time() - t
    M      *= temp
    print 'part2 finally', time.time() - t
    t       = time.time()

a = mp.arange( 30 )
b = mp.arange( 10 )
c = mp.linspace( 0, 100, 100 )

M = f1( a, b, c)

【问题讨论】:

    标签: python cython jit numba mpmath


    【解决方案1】:

    最好将 numba 与带有自定义装饰器的 vectorize 一起使用,如果未定义延迟操作将执行,这可能会导致进程变慢。 在我看来,与矢量化相比,Jit 很慢。

    【讨论】:

    • 欢迎来到 Stack Overflow!虽然这可能是解决问题的一个有价值的提示,但一个好的答案也可以证明解决方案。请edit 提供示例代码来说明您的意思。或者,考虑将其写为评论。
    相关资源