Python 中嵌入式循环的多线程



我有一个python代码,它可以对Shapefile中包含的数据进行一些操作。

在其他东西中,代码是这样做的:

 xxx=0
 for i in channels:
      ptsi=mat(shapes[i].points)
      xx = ptsi[:,0]
      yy = ptsi[:,1]
      nanx=argwhere(isnan(xx))      
      nany=argwhere(isnan(yy))
      if (nanx == nany and len(nanx) != 0):
          xx[nanx] = []
          yy[nany] = []
      elif (len(nanx) != 0 or len(nany) != 0):
          xx = []
          yy = []
      if (len(xx) > 0):          
       yyy = 0 
       dd = str(i*100/N_channels) + '%rr'
      # os.write(1,dd)
       dist = zeros(len(xx)-1)
       dist = dist_min
       for j in channels:
           pts=mat(shapes[j].points)
           xx2 = pts[:,0]
           yy2 = pts[:,1]
           nanx=argwhere(isnan(xx2))          
           nany=argwhere(isnan(yy2))
           if (nanx == nany and len(nanx) != 0):
            xx2[nanx] = []
            yy2[nany] = []
           elif (len(nanx) != 0 or len(nany) != 0):
            xx2 = []
            yy2 = []
           if (len(xx2) > 0):  
            if (i != j): 
               ds = gaa(xx,yy,xx2[0],yy2[0])
               de = gaa(xx,yy,xx2[-1],yy2[-1])
               nande = ~isnan(de)
               nands = ~isnan(ds)
               fe = np.argwhere(de<=dist)
               fs = np.argwhere(ds<=dist)
               nozeroe = array(where(de != 0))
               nozeroe = nozeroe[0]
               nozeros = array(where(ds != 0))
               nozeros = nozeros[0] 
               if(fs.size >0):
                    iis=array(np.argwhere(array(ds==min(ds))))
                    iis = iis.flatten()
                    iis = iis[0]
                    p1 = xxx + iis 
                    p2 = yyy
                    G.add_edge(p2,p1,weight=w_con)
               elif (fe.size > 0):
                    iie=array(np.argwhere(array(de==min(de))))
                    iie = iie.flatten()
                    iie = iie[0]
                    p1 = xxx + iie
                    p2 = yyy  + len(pts) -1
                    G.add_edge(p2,p1,weight=w_con)
           yyy = yyy + len(pts)
      xxx = xxx + len(ptsi)

基本上,代码扫描折线并搜索最小距离,以便合并到一个公共图形中(使用 Networkx)。这部分工作正常,除了这真的很慢,因为我处理了 100 多个数千个对象(当前版本大约需要 20 个小时)。

这些嵌入式循环效率不高,所以我想知道,使用多线程是否有帮助,如果是这样,我该如何修改代码的这一部分?如果 CUDA 或 OpenCL 能提供帮助,我对它很好。

感谢您的任何反馈!

由于全局解释器锁,Python 代码无法通过多线程充分利用多个内核,需要使用多处理才能充分利用多个内核。

更多的线程将无济于事;更多的进程可能会,但如果你可以使用 CUDA,这可能是一个不错的举措。线程只是允许多个事物共享进程CPU时间的一种方式,它不会加快慢速代码,但只会减慢您的速度。

最新更新