Python多处理-如何拆分工作负载以提高速度?


问题内容

我正在编写一个简单的代码来裁剪图像并保存它。
但是问题是图像数量大约为150,000+,我想提高速度。

因此,起初我用简单的for循环编写了代码,如下所示:

import cv2
import numpy
import sys

textfile=sys.argv[1]
file_list=open(textfile)
files=file_list.read().split('\n')
idx=0
for eachfile in files:
    image=cv2.imread(eachfile)
    idx+=1
    if image is None:
        pass
    outName=eachfile.replace('/data','/changed_data')
    if image.shape[0]==256:
        image1=image[120:170,120:170]
    elif image.shape[0]==50:
        image1=image
    cv2.imwrite(outName,image1)
    print idx,outName

这段代码花费了38秒的时间拍摄了90000张图片。但是,使用双核比单处理花费更多的时间,对于相同的90000张图像,大约需要48秒。

import cv2
import sys
import numpy
from multiprocessing import Pool

def crop(eachfile):
    image=cv2.imread(eachfile)
    idx+=1
    if image is None:
        pass
    outName=eachfile.replace('/data','/changed_data')
    if image.shape[0]==256:
        image1=image[120:170,120:170]
    elif image.shape[0]==50:
        image1=image
    cv2.imwrite(outName,image1)
    print idx,outName


if __name__=='__main__':
    textfile=sys.argv[1]
    file_list=open(textfile)
    files=file_list.read().split('\n')
    pool=Pool(2)
    pool.map(crop,files)

我在做正确的事情以加快流程吗?还是应该拆分列表并将每个列表发送给流程?

任何评论都认为我的代码很棒!!!

提前致谢!!!


问题答案:

您确实应该将任务分为两个核心。尝试使用此示例代码“稍作修改”。可以在这里找到OP
。您在那看到的data是提供图像的钩子。使用时defs在类下不起作用multiprocessing…如果尝试使用悲哀…您会从cPickle中得到错误…最新2.7版本存在一些困扰。在3.5或更高版本中不会出现。请享用!

import multiprocessing

def mp_worker((inputs, the_time)):
    print " Process %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs
    sys.stdout.flush()

def mp_handler():                           # Non tandem pair processing
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

def mp_handler_tandem():
    subdata = zip(data[0::2], data[1::2])
#    print subdata
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

#data = (['a', '1'], ['b', '2'], ['c', '3'], ['d', '4'])
data = (['a', '2'], ['b', '3'], ['c', '1'], ['d', '4'], 
        ['e', '1'], ['f', '2'], ['g', '3'], ['h', '4'])

if __name__ == '__main__':
    sys.stdout.flush()
#    print 'mp_handler():'
#    mp_handler()
#    print '---'
#    time.sleep(2)

#    print '\nmp_handler_tandem():'
#    mp_handler_tandem()
    print '---'
#    time.sleep(2)

    Multiprocess().qmp_handler()

在编辑器中工作:用于sys.stdout.flush()将输出刷新到屏幕上。

但也请在此处使用内核和拆分作业进行检查。