【问题标题】:Python Multiprocessing speed issuePython多处理速度问题
【发布时间】:2016-07-01 14:15:39
【问题描述】:

我有一个嵌套的 for 表单循环

while x<lat2[0]:
    while y>lat3[1]:
        if (is_inside_nepal([x,y])):
            print("inside")
        else:
            print("not")
        y = y - (1/150.0)
    y = lat2[1]
    x = x + (1/150.0)
#here lat2[0] represents a large number

现在这通常需要 50 秒来执行。 我已将此循环更改为多处理代码。

def v1find_coordinates(q):
  while not(q.empty()):

    x1 = q.get()
    x2 = x1 + incfactor
    while x1<x2:
        def func(x1): 
            while y>lat3[1]:
                if (is_inside([x1,y])):
                    print x1,y,"inside"
                else:
                    print x1,y,"not inside"
                y = y - (1/150.0)

        func(x1)
        y = lat2[1]
        x1 = x1 + (1/150.0)

incfactor = 0.7
xvalues = drange(x,lat2[0],incfactor)
#this drange function is to get list with increment factor as decimal
cores = mp.cpu_count()
q = Queue()
for i in xvalues:
    q.put(i)
for i in range(0,cores):
    p = Process(target = v1find_coordinates,args=(q,) )
    p.start()
    p.Daemon = True
    processes.append(p) 
for i in processes:
    print ("now joining")
    i.join()   

这个多处理代码也需要大约 50 秒的执行时间。这意味着两者之间没有时间差。

我也尝试过使用池。我还管理了块大小。我已经用谷歌搜索并搜索了其他stackoverflow。但是找不到满意的答案。

我能找到的唯一答案是花时间进行流程管理以使两者结果相同如果这是原因,那么我怎样才能让多处理工作获得更快的结果?

用 C 语言从 Python 实现会带来更快的结果吗?

我并不期待会有剧烈的结果,但根据常识,我们可以看出,在 4 核上运行应该比在 1 核上运行要快得多。但我得到了类似的结果。任何形式的帮助将不胜感激。

【问题讨论】:

  • 是队列可能是线程队列(导入队列)而不是多处理队列吗? (来自多处理导入队列)
  • 我自己还在学习多处理,但我读到如果你使用多线程,以处理器为中心的任务在速度上没有任何收获。我知道你说你以前用过游泳池,但也许再看看吧。
  • @HugoWalter 不,它不是导入队列
  • @Will.Evo 不,我这里没有使用多线程。我已经创建了流程。经过检查,有 4-5 个进程。

标签: python multithreading performance python-multiprocessing cpu-speed


【解决方案1】:

您似乎正在使用线程队列(来自队列导入队列)。这不能按预期工作,因为 Process 使用 fork() 并将整个队列克隆到每个工作进程中

用途:

from multiprocessing import Queue

【讨论】:

  • 我已经完成了从多处理导入队列而不是导入队列
猜你喜欢
  • 1970-01-01
  • 2019-09-01
  • 2016-08-28
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 2019-02-07
  • 2020-02-19
  • 1970-01-01
相关资源
最近更新 更多