openMP可以像多处理一样使用吗?
Can openMP be used like multiprocessing?
我有一个可以简单并行化的问题:我需要对 24 个 cdef 对象执行相同的操作。我知道我可以为此使用多进程,但是复制 data/starting 一个新进程需要的时间只要连续进行计算就可以了,所以什么也得不到。因此,openMP 可能是更好的选择。
我想要执行的操作与多处理类似:
multiprocess.map(f, list_of_cython_objects)
像下面这样的东西行得通吗? Why/why 不是吗?我知道我必须创建一个指向 cython 对象的指针数组,我不能使用列表。
from cython.parallel import prange, threadid
with nogil, parallel():
for i in prange(len(list_of_cython_objects), schedule='guided'):
f(list_of_cython_objects[i])
假设大多数 f
可以在没有 GIL 的情况下完成(即它使用 cdef class
的 cdef
属性)那么这可以很好地工作。唯一需要 GIL 的是索引列表,您可以轻松地将它放在 with gil
块中。
一个说明性的例子是:
from cython.parallel import prange, parallel
cdef class C:
cdef double x
def __init__(self,x):
self.x = x
cdef void f(C c) nogil:
c.x *= 2
def test_function():
list_of_cython_objects = [ C(x) for x in range(20) ]
cdef int l = len(list_of_cython_objects)
cdef int i
cdef C c
with nogil, parallel():
for i in prange(l, schedule='guided'):
with gil:
c = list_of_cython_objects[i]
f(c)
只要 with gil
块很小(就计算时间的比例而言),那么您应该获得预期的大部分并行化加速。
我有一个可以简单并行化的问题:我需要对 24 个 cdef 对象执行相同的操作。我知道我可以为此使用多进程,但是复制 data/starting 一个新进程需要的时间只要连续进行计算就可以了,所以什么也得不到。因此,openMP 可能是更好的选择。
我想要执行的操作与多处理类似:
multiprocess.map(f, list_of_cython_objects)
像下面这样的东西行得通吗? Why/why 不是吗?我知道我必须创建一个指向 cython 对象的指针数组,我不能使用列表。
from cython.parallel import prange, threadid
with nogil, parallel():
for i in prange(len(list_of_cython_objects), schedule='guided'):
f(list_of_cython_objects[i])
假设大多数 f
可以在没有 GIL 的情况下完成(即它使用 cdef class
的 cdef
属性)那么这可以很好地工作。唯一需要 GIL 的是索引列表,您可以轻松地将它放在 with gil
块中。
一个说明性的例子是:
from cython.parallel import prange, parallel
cdef class C:
cdef double x
def __init__(self,x):
self.x = x
cdef void f(C c) nogil:
c.x *= 2
def test_function():
list_of_cython_objects = [ C(x) for x in range(20) ]
cdef int l = len(list_of_cython_objects)
cdef int i
cdef C c
with nogil, parallel():
for i in prange(l, schedule='guided'):
with gil:
c = list_of_cython_objects[i]
f(c)
只要 with gil
块很小(就计算时间的比例而言),那么您应该获得预期的大部分并行化加速。