簡體   English   中英

python多處理慢

[英]python multiprocessing slow

我有一些代碼可以並行化對函數的調用。 在函數內部,我檢查文件是否存在,如果不存在,則創建它,否則不執行任何操作。

我發現如果文件確實存在,則與簡單的for循環相比,調用multiprocessing.process會耗費大量時間。 這是預期的還是我可以做些減少處罰的事情?

def fn():
    # Check if file exists, if yes then return else make the file
    if(not(os.path.isfile(fl))):
        # processing takes enough time to make the paralleization worth it
    else:
        print 'file exists'


pkg_num = 0
total_runs    = 2500
threads = []

while pkg_num < total_runs or len(threads):
    if(len(threads) < 3 and pkg_num < total_runs):
        t = multiprocessing.Process(target=fn,args=[])
        pkg_num = pkg_num + 1
        t.start()
        threads.append(t)
    else:
        for thread in threads:
            if not thread.is_alive():
                threads.remove(thread)

啟動流程會產生相當大的開銷-您必須權衡創建這些流程的開銷和通過使任務並發所獲得的性能優勢。 我不確定簡單的OS調用是否有足夠的優勢值得它。

另外,為了子孫后代,您應該真正檢查出current.comture.futures.ProcessPoolExecutor;。 方式,方式更清潔。 如果使用2.7,則可以反向移植它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM