2

我从这段代码开始计算一个简单的矩阵乘法。它在我的机器上以大约 7.85 秒的时间运行 %timeit。

为了加快速度,我尝试了 cython,将时间减少到 0.4 秒。我还想尝试使用 numba jit 编译器来查看是否可以获得类似的加速(用更少的努力)。但是添加 @jit 注释似乎给出了完全相同的时间(约 7.8 秒)。我知道它无法确定 calculate_z_numpy() 调用的类型,但我不确定我能做些什么来强制它。有任何想法吗?

from numba import jit
import numpy as np

@jit('f8(c8[:],c8[:],uint)')
def calculate_z_numpy(q, z, maxiter):
    """use vector operations to update all zs and qs to create new output array"""
    output = np.resize(np.array(0, dtype=np.int32), q.shape)
    for iteration in range(maxiter):
        z = z*z + q
        done = np.greater(abs(z), 2.0)
        q = np.where(done, 0+0j, q)
        z = np.where(done, 0+0j, z)
        output = np.where(done, iteration, output)
    return output

def calc_test():
    w = h = 1000
    maxiter = 1000
    # make a list of x and y values which will represent q
    # xx and yy are the co-ordinates, for the default configuration they'll look like:
    # if we have a 1000x1000 plot
    # xx = [-2.13, -2.1242,-2.1184000000000003, ..., 0.7526000000000064, 0.7584000000000064, 0.7642000000000064]
    # yy = [1.3, 1.2948, 1.2895999999999999, ..., -1.2844000000000058, -1.2896000000000059, -1.294800000000006]
    x1, x2, y1, y2 = -2.13, 0.77, -1.3, 1.3

    x_step = (float(x2 - x1) / float(w)) * 2
    y_step = (float(y1 - y2) / float(h)) * 2
    y = np.arange(y2,y1-y_step,y_step,dtype=np.complex)
    x = np.arange(x1,x2,x_step)
    q1 = np.empty(y.shape[0],dtype=np.complex)
    q1.real = x
    q1.imag = y
    # Transpose y
    x_y_square_matrix = x+y[:, np.newaxis] # it is np.complex128
    # convert square matrix to a flatted vector using ravel
    q2 = np.ravel(x_y_square_matrix)
    # create z as a 0+0j array of the same length as q
    # note that it defaults to reals (float64) unless told otherwise
    z = np.zeros(q2.shape, np.complex128)
    output = calculate_z_numpy(q2, z, maxiter)
    print(output)

calc_test()
4

1 回答 1

4

我想出了如何在其他人的帮助下做到这一点。

@jit('i4[:](c16[:],c16[:],i4,i4[:])',nopython=True)
def calculate_z_numpy(q, z, maxiter,output):
    """use vector operations to update all zs and qs to create new output array"""
    for iteration in range(maxiter):
        for i in range(len(z)):
            z[i] = z[i] + q[i]
            if z[i] > 2:
                output[i] = iteration
                z[i] = 0+0j
                q[i] = 0+0j
    return output

我学到的是使用 numpy 数据结构作为输入(用于打字),但在使用 c 之类的范例进行循环。

这在 402 毫秒内运行,这比 cython 代码 0.45 秒快一点,因此对于显式重写循环的相当少的工作,我们有一个比 C(just) 更快的 python 版本。

于 2014-12-07T19:13:49.290 回答