Cython 并行多线程是顺序的

时间:2020-12-27 13:09:22

标签: python arrays multithreading parallel-processing cython

我想在 Cython 中使用多线程,我有数组,我希望每个线程在数组的不同范围内工作,这是一个小例子。

`@cython.boundscheck(False)
 @cython.wraparound(False)
 cdef void worker(int *P,int *R1, int *R2,int n):
    cdef int i
    #n=number of threads
    with nogil, parallel(num_threads=n):
      for i in prange(n):
        ww(P,R1[i],R2[i])`


@cython.boundscheck(False)
@cython.wraparound(False)
cdef void ww(int *P,int r1, int r2) nogil:
   cdef int i
   for i in range(r1,r2):
        P[i]=1

如果数组大小增加到足够多,执行时间会变成连续的,为什么?如果我使用 memoryview 而不是数组,时间会比顺序更糟糕。不要看代码是怎么工作的,这只是一个例子,因为我的代码很长,我必须并行使用数组或内存视图,没有线程访问与另一个线程相同的位置。

有什么帮助或帮助吗?会不会是访问数组存在互斥?

主要有:

@cython.boundscheck(False)

@cython.wraparound(False)
cpdef fit():
  cdef int l=5000000
  cdef int repeat=10000
  
  cdef int n_Thread=6
 
  cdef int *R1=<int *> malloc(n_Thread* sizeof(int))
  cdef int *R2=<int *> malloc(n_Thread* sizeof(int))
  makeR1R2(R1,R2,n,l)

  cdef int *P=<int *> malloc(l* sizeof(int))

  
  t1=time.time()

  #Parallel
  for i in range(repeat):
    worker(P,R1,R2,n)

  t2=time.time()
  print("1 ",t2-t1)

  #Sequential
  for i in range(repeat):
    worker2(P,l)

  print("2 ",time.time()-t2)
  free(P)
  

有设置:

from setuptools import Extension, setup
from Cython.Build import cythonize

ext_modules = [
 Extension(
    "fit",
    ["fit.pyx"],
    extra_compile_args=['-fopenmp'],
    extra_link_args=['-fopenmp'],
    )
 ]

 setup(
 name='fit-popf',
 ext_modules=cythonize(ext_modules),
 )

0 个答案:

没有答案
相关问题