本文翻译改写自:https://medium.com/@ageitgey/quick-tip-speed-up-your-python-data-processing-scripts-with-process-pools-cf275350163amedium.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中通过简单的三条命令,我们就可以最大化电脑的性能。