[使用多重处理的过程花费更多时间

问题描述 投票:0回答:1

我有50个测试需要同时执行。

[我发现其中一个测试“ A”花费1分钟才能完成(没有多重处理)。

我也尝试选择测试“ A”和其他一些测试(约5个)以进行多处理,“ A”也要花费1分钟。

但是,如果我使用多处理程序执行所有测试,则测试“ A”将花费近30分钟的时间才能完成。

测试“ A”开始得很早,但最后结束了。如何找到根本原因?

我怎么知道池是否总是使用所有工作程序?

(我要打印当前正在运行的进程。)

            from multiprocessing import Pool

            results = []
            pool = Pool(processes=10)  # start 10 worker processes
            unfinishedTest = testList

            for i in range(0, len(testList)):
                async_result = pool.apply_async(run_test, kwds={'test':testList[i]})
                results.append([async_result, testList[i]])

            while True:
                for r in results:
                    if r[0].ready() and r[1] in unfinishedTest: #Return whether the call has completed.
                        unfinishedTest.remove(r[1])
                        print(r[1], "finished")
                        print("unfinished " + str(len(unfinishedTest)) + " test:", unfinishedTest)

                if len(unfinishedTest) == 0:
                    print("All tests done.")
                    break
                time.sleep(0.25)

            pool.close()
            pool.join()
python multiprocessing python-multiprocessing pool multiprocess
1个回答
0
投票

问题出在您的run_test函数中。 而且您无能为力。

CPython不会从多个内核中受益。如果您的run_test函数主要是面向CPU的,那么更多的线程会使问题变得更糟,因为所有线程都将争夺CPU,并且最终结果是,停止线程所花费的时间比实际工作要多。

仅使用一个线程,您的函数所做的一切就完成了。一个CPU内核可以做到的最快速度。

另一方面,如果您的函数花大量时间等待IO,则线程可以提供帮助。很多。

您真正得到的最好的解释是来自唯一的David Beazley。 Understanding the Python GIL

因此,从本质上讲,您的程序花费大量时间来唤醒无法运行的线程,并停止可以运行的线程,这样做。

© www.soinside.com 2019 - 2024. All rights reserved.