我已经将下面的代码编写为Cython中并行计算的一个简单示例。在我的示例中,我创建了两个工作对象并让它们并行运行。我想概括这个实现来使用可变数量的worker。问题是我无法找到一种方法来存储一个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之前。
答案 0 :(得分:1)
据我所知,nogil
不支持Python对象的索引(以及强制,......)。因此,在将Workers
存储在内置Python list
中时,我们会收到以下消息:
cdef list workers
workers = [Worker(), Worker(), Worker(), Worker()]
消息:
在没有gil的情况下不允许索引Python对象
您可以尝试这样的事情 (经测试,似乎工作正常) :
此处的解决方法是对nogil
部分中使用的所有内容使用C语法:
cdef PyObject ** workers
cdef int * buf_sizes
cdef FLOAT_t ** buffers
使用malloc
中的旧libc.stdlib
分配这些数组。
<强>代码:强>
# 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
# Pyobject is the C representation of a Python object
# This allows casts in both ways...
cimport cython
from cpython cimport PyObject
# C memory alloc features
from libc.stdlib cimport malloc, free
cdef FLOAT_t MAXfloat64 = np.float64(np.inf)
cdef class Parent:
cdef cnp.ndarray numbers
cdef unsigned int i
cdef PyObject ** workers
cdef int nb_workers
cdef int * buf_sizes
cdef FLOAT_t ** buffers
def __init__(Parent self, list numbers, int n_workers):
self.numbers = <cnp.ndarray[FLOAT_t, ndim=1]> np.array(numbers,dtype=float)
# Define number of workers
self.nb_workers = n_workers
self.workers = <PyObject **>malloc(self.nb_workers*cython.sizeof(cython.pointer(PyObject)))
# Populate pool
cdef int i
cdef PyObject py_obj
cdef object py_workers
py_workers = [] # For correct ref count
for i in xrange(self.nb_workers):
py_workers.append(Worker())
self.workers[i] = <PyObject*>py_workers[i]
self.init_buffers()
cdef init_buffers(Parent self):
cdef int i, j
cdef int num_threads
cdef int pos, pos_end
cdef int buf_size
num_threads = self.nb_workers
buf_size = len(self.numbers) // num_threads
# Init buffers
self.buffers = <FLOAT_t **>malloc(self.nb_workers * cython.sizeof(cython.pointer(FLOAT_t)))
self.buf_sizes = <int *>malloc(self.nb_workers * cython.sizeof(int))
pos = 0
buf_size = len(self.numbers) // num_threads
for i in xrange(self.nb_workers):
# If we are treating the last worker do everything left
if (i == self.nb_workers-1):
buf_size = len(self.numbers) - pos
self.buf_sizes[i] = buf_size
pos_end = pos + buf_size
self.buffers[i] = <FLOAT_t *>malloc(buf_size * cython.sizeof(FLOAT_t))
for j in xrange(pos, pos_end):
self.buffers[i][j-pos] = <FLOAT_t>self.numbers[j]
pos = pos + buf_size
cpdef run(Parent self, bint use_parallel):
cdef int i
cdef FLOAT_t best
# Run the workers
if use_parallel:
print 'parallel'
with nogil:
for i in prange(self.nb_workers, num_threads=self.nb_workers):
# Changed "FLOAT_t[:]" python object to C array "FLOAT_t *"
(<Worker>self.workers[i]).run(<FLOAT_t *>self.buffers[i], self.buf_sizes[i])
else:
print 'serial'
for i in xrange(self.nb_workers):
(<Worker>self.workers[i]).run(<FLOAT_t *>self.buffers[i], self.buf_sizes[i])
# Make sure they ran
for i in xrange(self.nb_workers):
print (<Worker>self.workers[i]).output
# Choose the worker that had the best solution
best = MAXfloat64
for i in xrange(self.nb_workers):
if ((<Worker>self.workers[i]).output < best):
best = (<Worker>self.workers[i]).output
return best
cdef class Worker:
cdef public float output
def __init__(Worker self):
self.output = 0.0
# Changed "FLOAT_t[:]" python object to C dyn array "FLOAT_t *"
cdef void run(Worker self, FLOAT_t * numbers, unsigned int buffer_size) nogil:
cdef unsigned int i, j
cdef unsigned int n = buffer_size
cdef FLOAT_t best
cdef bint first = True
cdef FLOAT_t value
# Added initialization
best = MAXfloat64
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, 7)
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
-1.0
-1.0
-1.0
-1.0
-1.0
Serial Result: -1.000000
Serial Time: 2.741364
parallel
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
Parallel Result: -1.000000
Parallel Time: 0.536419
希望这符合您的要求,或者至少提出一些想法......请分享您的最终实施......