使用Cython启用并行性

时间:2017-10-27 14:22:15

标签: multithreading openmp cython cythonize

我试图让Cython的prange包的parallel函数起作用,似乎没有效果的并行性。为了获得MWE,我已经从书Cython: A Guide for Python Programmers中获取了示例代码,并通过添加一些print语句对其进行了一些修改。示例代码可以在github免费获得,我所指的代码位于:examples / 12-parallel-cython / 02-prange-parallel-loops /.

以下是我对julia.pyx文件的修改。

# distutils: extra_compile_args = -fopenmp
# distutils: extra_link_args = -fopenmp

from cython cimport boundscheck, wraparound
from cython cimport parallel

import numpy as np

cdef inline double norm2(double complex z) nogil:
    return z.real * z.real + z.imag * z.imag


cdef int escape(double complex z,
                double complex c,
                double z_max,
                int n_max) nogil:

    cdef:
        int i = 0
        double z_max2 = z_max * z_max

    while norm2(z) < z_max2 and i < n_max:
        z = z * z + c
        i += 1

    return i


@boundscheck(False)
@wraparound(False)
def calc_julia(int resolution, double complex c,
               double bound=1.5, double z_max=4.0, int n_max=1000):

    cdef:
        double step = 2.0 * bound / resolution
        int i, j
        double complex z
        double real, imag
        int[:, ::1] counts

    counts = np.zeros((resolution+1, resolution+1), dtype=np.int32)

    for i in parallel.prange(resolution + 1, nogil=True,
                    schedule='static', chunksize=1):
        real = -bound + i * step
        for j in range(resolution + 1):
            imag = -bound + j * step
            z = real + imag * 1j
            counts[i,j] = escape(z, c, z_max, n_max)

    return np.asarray(counts)

@boundscheck(False)
@wraparound(False)
def julia_fraction(int[:,::1] counts, int maxval=1000):
    cdef:
        unsigned int thread_id
        int total = 0
        int i, j, N, M
    N = counts.shape[0]; M = counts.shape[1]
    print("N = %d" % N)
    with nogil:
        for i in parallel.prange(N, schedule="static", chunksize=10):
            thread_id = parallel.threadid()
            with gil:
                print("Thread %d." % (thread_id))
            for j in range(M):
                if counts[i,j] == maxval:
                    total += 1
    return total / float(counts.size)

当我使用

给出的setup_julia.py进行编译时
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

setup(name="julia",
      ext_modules=cythonize(Extension('julia', ['julia.pyx'], extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])))

使用命令

python setup_julia.py build_ext --inplace

并运行run_julia.py文件,我发现for循环的所有实例只使用一个线程 - Thread 0。终端输出如下所示。

poulin8:02-prange-parallel-loops poulingroup$ python run_julia.py 
time: 0.892143
julia fraction: N = 1001
Thread 0.
Thread 0.
Thread 0.
Thread 0.
.
.
.
.
Thread 0.
0.236994773458

据我所知,for循环只是并行运行。有人可以指导我在启动for循环以在多个线程中分配负载时必须做些什么吗? 我还尝试将系统变量OMP_NUM_THREADS设置为大于1的某个数字,并且没有效果。

我在OSX 10.11.6上运行测试,使用Python 2.7.10和gcc 5.2.0。

1 个答案:

答案 0 :(得分:0)

我在Windows 7上遇到了同样的问题。 它正在运行串行。 注意到编译消息:

python setup_julia.py build_ext --inplace

  

cl:命令行警告D9002:忽略未知选项'-fopenmp'

显然,在Visual Studio中,它必须为-openmp

# distutils: extra_compile_args = -openmp
# distutils: extra_link_args = -openmp

现在并行运行。

如@danny所述,您可以使用fprintf:

from cython.parallel cimport prange, threadid
from libc.stdio cimport stdout, fprintf

def julia_fraction(int[:,::1] counts, int maxval=1000):
   ...
   thread_id = threadid()
   fprintf(stdout, "%d\n", <int>thread_id)
   ...