Python中运行并行任务技巧

yipeiwu_com5年前Python基础

示例

标准线程多进程,生产者/消费者示例:
Worker越多,问题越大

复制代码 代码如下:

# -*- coding: utf8 -*-

import os
import time
import Queue
import threading
from PIL import Image

def create_thumbnail(filename, size=(128, 128)):
    try:
        fp, fmt = filename.rsplit('.', 1)
        im = Image.open(filename)
        im.thumbnail(size, Image.ANTIALIAS)
        im.save((fp + '_'+'x'.join(str(i) for i in size) + '.'+fmt), im.format)
        return '%s thumbnail success!' % filename
    except Exception:
        return '%s thumbnail failed!' % filename


def get_image_paths(folder):
    return [os.path.join(folder, f) for f in os.listdir(folder) if 'png' in f]


class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue

    def run(self):
        while True:
            content = self._queue.get()
            if isinstance(content, str) and content == 'quit':
                break
            respone = create_thumbnail(content)
        print 'Bye bye!'


def Producer():
    filenames = get_image_paths('images')
    queue = Queue.Queue()
    worker_threads = build_worker_pool(queue, 4)
    start_time = time.time()

    for filename in filenames:
        queue.put(filename)
    for worker in worker_threads:
        queue.put('quit')
    for worker in worker_threads:
        worker.join()

    print time.time() - start_time


def build_worker_pool(queue, size):
    workers = []
    for _ in range(size):
        worker = Consumer(queue)
        worker.start()
        workers.append(worker)
    return workers


if __name__ == '__main__':
    Producer()

map

Map能够处理集合按顺序遍历,最终将调用产生的结果保存在一个简单的集合当中。

复制代码 代码如下:

# -*- coding: utf8 -*-

import os
import time
from multiprocessing import Pool
from PIL import Image

def create_thumbnail(filename, size=(128, 128)):
    try:
        fp, fmt = filename.rsplit('.', 1)
        im = Image.open(filename)
        im.thumbnail(size, Image.ANTIALIAS)
        im.save((fp + '_'+'x'.join(str(i) for i in size) + '.'+fmt), im.format)
        return '%s thumbnail success!' % filename
    except Exception:
        return '%s thumbnail failed!' % filename


def get_image_paths(folder):
    return [os.path.join(folder, f) for f in os.listdir(folder) if 'png' in f]


def main():
    filenames = get_image_paths('images')
    start_time = time.time()
   
    pool = Pool(4)
    pool.map(create_thumbnail, filenames)
    pool.close()
    pool.join()

    print time.time() - start_time


if __name__ == '__main__':
    main()

相关文章

Python使用matplotlib绘制余弦的散点图示例

Python使用matplotlib绘制余弦的散点图示例

本文实例讲述了Python使用matplotlib绘制余弦的散点图。分享给大家供大家参考,具体如下: 一 代码 import numpy as np import pylab as...

python scrapy重复执行实现代码详解

这篇文章主要介绍了python scrapy重复执行实现代码详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Scrapy是一个为了...

django的ORM操作 删除和编辑实现详解

向server端传送数据 有2中方法,1 是 通过url 地址, 2 是通过路径 向server端传参数方式 1,通过数据 http://127.0.0.1:8000/blog/&#...

Django学习之文件上传与下载

本文实例为大家分享了Django文件上传与下载的具体代码,供大家参考,具体内容如下 文件上传 1.新建django项目,创建应用stu: python manage.py start...

Python 把序列转换为元组的函数tuple方法

tuple函数功能和list功能很相似,以序列为参数并把它转换为元组 >>> tuple([1,2,3]) (1, 2, 3) >>> tuple...