我编写了下面的代码作为 Cython 中并行计算的简单示例。在我的示例中,我创建了两个工作对象并让它们并行运行。我想概括这个实现以使用可变数量的工人。问题是我找不到存储 Worker 对象数组并使用 nogil 访问它们的方法。有没有办法做到这一点?显然,我可以使用下面的技术(最多一些合理的硬编码工人数量)一起破解一些合理的东西,但如果它存在的话,我想要一些更优雅和可维护的东西。
这是代码。关键部分在 if use_parallel 下:
# distutils: language = c
# cython: cdivision = True
# cython: boundscheck = False
# cython: wraparound = False
# cython: profile = False
cimport numpy as cnp
import numpy as np
from cython.parallel import parallel, prange
from libc.math cimport sin
cimport openmp
cnp.import_array()
ctypedef cnp.float64_t FLOAT_t
ctypedef cnp.intp_t INT_t
ctypedef cnp.ulong_t INDEX_t
ctypedef cnp.uint8_t BOOL_t
cdef class Parent:
cdef cnp.ndarray numbers
cdef unsigned int i
cdef Worker worker1
cdef Worker worker2
def __init__(Parent self, list numbers):
self.numbers = <cnp.ndarray[FLOAT_t, ndim=1]> np.array(numbers,dtype=float)
self.worker1 = Worker()
self.worker2 = Worker()
cpdef run(Parent self, bint use_parallel):
cdef unsigned int i
cdef float best
cdef int num_threads
cdef cnp.ndarray[FLOAT_t, ndim=1] numbers = <cnp.ndarray[FLOAT_t, ndim=1]> self.numbers
cdef FLOAT_t[:] buffer1 = self.numbers[:(len(numbers)//2)]
buffer_size1 = buffer1.shape[0]
cdef FLOAT_t[:] buffer2 = self.numbers[(len(numbers)//2):]
buffer_size2 = buffer2.shape[0]
# Run the workers
if use_parallel:
print 'parallel'
with nogil:
for i in prange(2, num_threads=2):
if i == 0:
self.worker1.run(buffer1, buffer_size1)
elif i == 1:
self.worker2.run(buffer2, buffer_size2)
else:
print 'serial'
self.worker1.run(buffer1, buffer_size1)
self.worker2.run(buffer2, buffer_size2)
#Make sure they both ran
print self.worker1.output, self.worker2.output
# Choose the worker that had the best solution
best = min(self.worker1.output, self.worker2.output)
return best
cdef class Worker:
cdef public float output
def __init__(Worker self):
self.output = 0.0
cdef void run(Worker self, FLOAT_t[:] numbers, unsigned int buffer_size) nogil:
cdef unsigned int i
cdef unsigned int j
cdef unsigned int n = buffer_size
cdef FLOAT_t best
cdef bint first = True
cdef FLOAT_t value
for i in range(n):
for j in range(n):
value = sin(numbers[i]*numbers[j])
if first or (value < best):
best = value
first = False
self.output = best
我的测试脚本如下所示:
from parallel import Parent
import time
data = list(range(20000))
parent = Parent(data)
t0 = time.time()
output = parent.run(False)
t1 = time.time()
print 'Serial Result: %f' % output
print 'Serial Time: %f' % (t1-t0)
t0 = time.time()
output = parent.run(True)
t1 = time.time()
print 'Parallel Result: %f' % output
print 'Parallel Time: %f' % (t1-t0)
它产生这个输出:
serial
-1.0 -1.0
Serial Result: -1.000000
Serial Time: 6.428081
parallel
-1.0 -1.0
Parallel Result: -1.000000
Parallel Time: 4.006907
最后,这是我的 setup.py:
from distutils.core import setup
from distutils.extension import Extension
import sys
import numpy
#Determine whether to use Cython
if '--cythonize' in sys.argv:
cythonize_switch = True
del sys.argv[sys.argv.index('--cythonize')]
else:
cythonize_switch = False
#Find all includes
numpy_include = numpy.get_include()
#Set up the ext_modules for Cython or not, depending
if cythonize_switch:
from Cython.Distutils import build_ext
from Cython.Build import cythonize
ext_modules = cythonize([Extension("parallel.parallel", ["parallel/parallel.pyx"],include_dirs = [numpy_include],
extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])])
else:
ext_modules = [Extension("parallel.parallel", ["parallel/parallel.c"],include_dirs = [numpy_include],
extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])]
#Create a dictionary of arguments for setup
setup_args = {'name':'parallel-test',
'version':'0.1.0',
'author':'Jason Rudy',
'author_email':'jcrudy@gmail.com',
'packages':['parallel',],
'license':'LICENSE.txt',
'description':'Let\'s try some parallel programming in Cython',
'long_description':open('README.md','r').read(),
'py_modules' : [],
'ext_modules' : ext_modules,
'classifiers' : ['Development Status :: 3 - Alpha'],
'requires':[]}
#Add the build_ext command only if cythonizing
if cythonize_switch:
setup_args['cmdclass'] = {'build_ext': build_ext}
#Finally
setup(**setup_args)
它必须用 gcc 编译,你可以在 mac 上用
export CC=gcc
在运行 setup.py 之前。