这是我第一次尝试将 JIT 用于 python,这是我想要加速的用例。我读了一些关于 numba 的内容,它看起来很简单,但是下面的代码没有提供任何加速。请原谅我可能犯的任何明显错误。
我还尝试按照 cython 的基本教程的建议进行操作,但时间上没有区别。 http://docs.cython.org/src/tutorial/cython_tutorial.html
我猜我必须做一些类似声明变量的事情?使用其他库?只为所有内容使用 for 循环?我将不胜感激任何可以参考的指导或示例。
例如,我从上一个问题中了解到,与 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)