python并行处理技术_多核并行处理--(python)

本文翻译改写自:https://medium.com/@ageitgey/quick-tip-speed-up-your-python-data-processing-scripts-with-process-pools-cf275350163a​medium.com

随着多核笔记本、台式机的越来越普及,你的电脑性能是否充分使用。但是当在日常编写程序时,往往却只使用了其中的一核,这样太浪费电脑的性能了。通过阅读本篇博客,你将会通过使用简单三行命令,在python中使用多核并行处理,最大化电脑的性能。

在python 中简单的三条命令语句是:

import concurrent.futures

with concurrent.futures.ProcessPoolExecutor() as executor:

executor.map()

下面通过将单核程序处理和多核程序处理进行对比,来分析多核处理的速度提升。测试电脑为2核。

下面的处理程序为将文件夹里的501张图片进行亮度提升,并将结果保存在某文件夹下。

单核处理程序:

# # ##单核处理程序

import glob

from PIL import ImageFile

from PIL import Image

from PIL import ImageEnhance

ImageFile.LOAD_TRUNCATED_IMAGES = True

def make_image_brightness(image):

# print(image)

name = image.split("/")[-1]

print(name)

image = Image.open(image)

enh_bri = ImageEnhance.Brightness(image)

brightness = 1.5

image_brightened = enh_bri.enhance(brightness)

image_brightened.save("./img/{}".format(name))

# Loop through all jpeg files in the folder and make a thumbnail for each

for image_file in glob.glob("/Users/admin/datasets/5k_test_set/input/*.jpg"):

make_image_brightness(image_file)

多核处理程序

import glob

import concurrent.futures

from PIL import ImageFile

from PIL import Image

from PIL import ImageEnhance

ImageFile.LOAD_TRUNCATED_IMAGES = True

def make_image_brightness(image):

# print(image)

name = image.split("/")[-1]

print(name)

image = Image.open(image)

enh_bri = ImageEnhance.Brightness(image)

brightness = 1.5

image_brightened = enh_bri.enhance(brightness)

image_brightened.save("./img1/{}".format(name))

# Create a pool of processes. By default, one is created for each CPU in your machine.

with concurrent.futures.ProcessPoolExecutor() as executor:

# Get a list of files to process

image_files = glob.glob("/Users/admin/datasets/5k_test_set/input/*.jpg")

# # Process the list of files, but split the work across the process pool to use all CPUs!

executor.map(make_image_brightness, image_files)

下面将单核和多核的处理时间进行对比。

测试命令为:

time python 单核处理.py

time python 多核并行处理.py

输出结果为:

单核处理 349.28s user 18.08s system 99% cpu 6:09.58 total

多核并行处理 565.25s user 27.85s system 360% cpu 2:44.72 total

在结果中我们发现total(代表最终的运行时间)为6分钟和 2.5分钟,处理时间大概提升了两倍。但是大家可能对user和system表示困惑,为什么这两个时间都增加了?这是因为在多核处理中,user显示的最终时间是每个核的运行时间相加,所以多核处理会比单核处理的时间多很多。

下面我们再来看下电脑cpu使用情况:

第一张图片表示单核处理的情况,我们可以看到电脑的闲置大概为70%,而在第二张图片里面,我们可以看到电脑几乎在没有闲置的在工作。

在python中通过简单的三条命令,我们就可以最大化电脑的性能。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值