如何在python中与mpmath/gmpy一起有效地使用JIT



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

我也试着按照cython的基本教程的建议去做,但同样没有时间差异。http://docs.cython.org/src/tutorial/cython_tutorial.html

我想我必须做一些事情,比如声明变量?使用其他库?只用于所有内容的循环?我将感谢任何我可以参考的指导或例子。

例如,我从前面的一个问题中知道,与numpy及其解决方案相比,mpmath中的Elementwise操作速度较慢,使用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)

最好使用带有矢量化的numba和自定义装饰器,如果没有定义,将执行懒惰操作,这可能会导致进程减慢。在我看来,与矢量化相比,Jit是缓慢的。

最新更新