python 多线程&多进程&rxpy的效率比较

因为python的GIL的问题, 一般来说对于计算密集型的代码, 效率一边如下: 多进程 < 普通 < 多线程, 多进程效率最高, 多线程由于切换context的原因, 反倒效率不佳。

对于一个reactive编程的死忠, 用python多线程编程, 还没有看完api, 就想到了用rxpy来实现如何呢?结果官网上有这么一段话:

Keep in mind Python's GIL has the potential to undermine your concurrency performance, as it prevents multiple threads from accessing the same line of code simultaneously. Libraries like NumPy can mitigate this for parallel intensive computations as they free the GIL. RxPy may also minimize thread overlap to some degree. Just be sure to test your application with concurrency and ensure there is a performance gain.

大概意思就是rxpy能减轻GIL带来的问题, 并且还是每次都要测试下你写的代码是得到了性能的优化。

作为一个调库君, python暂时不打算太深入的情况下, 我不准备深究GIL的问题, 以从根本知道哪些情况下会带来效率提升, 但是简答的一个评测还是有必要的, OK, let's try!

首先上测试代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import multiprocessing as mp
import threading as td
import sys
from threading import current_thread

import time
from rx import Observable
from rx.concurrency import ThreadPoolScheduler


def intense_calculation(s):
    temp = 0.8
    for i in range(100000):
        temp += (i ** 2 + i ** 0.3 + i ** 0.5) / (i ** 1.2 + i * 0.02 + 0.05)
    return s


def do_20_calculation(name):
    for i in range(20):
        print("PROCESS {0} {1} {2} @ {3}".format(name, current_thread().name, intense_calculation(i),
                                                 time.time() - start_time)),


def proc_proces(name):
    mp.Process(target=do_20_calculation, args=(name,)).start()


def proc_thread(name):
    td.Thread(target=do_20_calculation, args=(name,)).start()


def proc_rx2(name, pool_scheduler):
    # Observable.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]) \
    # .do_action(lambda s: print("begin PROCESS {0} {1} {2}".format(name, current_thread().name, s)))
    for i in range(20):
        Observable.just(i) \
            .subscribe_on(pool_scheduler) \
            .map(lambda s: intense_calculation(s)) \
            .subscribe(on_next=lambda s: print("PROCESS {0} {1} {2}".format(name, current_thread().name, s)),
                       on_error=lambda e: print(e),
                       on_completed=lambda: print("PROCESS %s done! @ %.3f" % (name, time.time() - start_time)))


def proc_normal(name):
    for i in range(20):
        s = intense_calculation(i)
        used_time = time.time() - start_time
        print("PROCESS? {0} thread {1} task {2} done @ {3}".format(name, current_thread().name, s, used_time))


def main(type, proc_num, add_to_core_num):
    global start_time
    # calculate number of CPU's, then create a ThreadPoolScheduler with that number of threads
    optimal_thread_count = mp.cpu_count()
    print("has %d cpu cores" % optimal_thread_count)
    pool_scheduler = ThreadPoolScheduler(optimal_thread_count + add_to_core_num)
    start_time = time.time()
    if type == "thread":
        for i in range(proc_num):
            proc_thread("%d" % i)
    elif type == "process":
        for i in range(proc_num):
            proc_proces("%d" % i)
    elif type == "rx":
        for i in range(proc_num):
            proc_rx2("%d" % i, pool_scheduler)
    else:
        for i in range(proc_num):
            proc_normal("%d" % i)
        print("end @ %.2f" % (time.time() - start_time))

    input("Press any key to exit\n")


start_time = 0

if __name__ == "__main__":
    main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))

简单解释下功能, 就是根据输入的type, 测试不同的调用方式, 当传入的参数迭代8次的时候,意味着单线程会循环8*20次调用intense_calculation, process会启动8个进程,每个进程调用20次, thread会启动8个线程, 运行20次, rx比较特别, 它会启动8个线程, 但是每个线程从线程池中获取, 线程池的大小为8.
为什么取8, 因为我测试的ubuntu机器正好8核(逻辑核)。
都传入8次的时候, 结果如下:

线程调用方式 迭代此处 耗时(秒)
单线程循环 8 21.92
rx方式 8 45.35
线程 8 45.23
进程 8 3.1
rx 16 90.854
线程 16 92.62
进程 16 5.91

从上面的表格可以看出,当前的测试代码下(cpu comsuming&same code been called), 基本来说rx还是不能避免thread的低效的问题,基本延续了之前的结论。rxPy估计只是在线程更多的时候,并且线程调度频繁的时候,使用的线程池有点点优势,知道没有明显降低性能, 还是值得一用的。

结论

多进程模式吊打多线程, 多进程真的能充分给你用多核的优势。


继续测试使用多进程进行guezli转换的速度

ps: 这个才是我看python多线程&多进程的初衷

附上测试代码,简单来说,启动了cpu核数一样的进程, 每个进程会获取queue传入的数据来进行压缩, 在ubuntu 16.04机器上,cpu: 8核 Intel(R) Xeon(R) CPU E5-2609 v2 @ 2.50GHz, 2个物理cpu的情况下, 压缩23张 260*364大小的图(其实是三轮, 所以到24张图估计时间也一样, 同时不同图耗时可能不一样),耗时74.70秒, 未调整guetzli的参数。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import multiprocessing as mp
import os
import sys
import threading as td
import time
from threading import current_thread

from rx import Observable
from rx.concurrency import ThreadPoolScheduler


def do_encode(path, out_path):
    print("will process %s %s" % (path, os.getpid()))
    os.system('guetzli ' + path + " " + out_path)
    print("process done:  %s" % path)
    return path


def do_process(queue):
    while True:
        info = queue.get()
        if info["type"] == "quit":
            # print("{0} get quit command".format(os.getpid()))
            break
        elif info["type"] == "zipJpg":
            print("{0} get zip jpeg".format(os.getpid()))
            do_encode(info["path"], info["out_path"])
        else:
            print("{0} get wrong command".format(os.getpid()))
    print("{0} quits".format(os.getpid()))


def main(path):
    global start_time

    # calculate number of CPU's, then create a ThreadPoolScheduler with that number of threads
    optimal_thread_count = mp.cpu_count()
    print("has %d cpu cores" % optimal_thread_count)
    pool_scheduler = ThreadPoolScheduler(optimal_thread_count)
    work_process = []

    queue = mp.Queue(optimal_thread_count)

    # 启动线程
    for i in range(optimal_thread_count):
        p = mp.Process(target=do_process, args=(queue,))
        work_process.append(p)
        p.start()

    pictures = []
    out_pictures = []
    out_dir = os.path.join(path, "out")
    os.system("rm -rf %s" % out_dir)
    os.system("mkdir %s" % out_dir)
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".jpg") or file.endswith(".png"):
                pictures.append(os.path.join(root, file))
                out_pictures.append(os.path.join(out_dir, file))

    # for f in pictures:
    #     print(f)

    def on_complete():
        # 停止所有的进程
        for ii in range(optimal_thread_count):
            print("send {0} to quit".format(ii))
            queue.put({"type": "quit"})
        print("onComplete")

    def send_message(paths):
        queue.put({"type": "zipJpg", "path": paths[0], "out_path": paths[1]})
        return paths[0]

    # 向进程发送消息
    Observable.from_(zip(pictures, out_pictures)).map(
        lambda paths: send_message(paths)).subscribe_on(pool_scheduler).subscribe(
        on_next=lambda s: print("send {0} on thread {1} done.".format(s, current_thread().name)),
        on_error=lambda e: print("onError", e),
        on_completed=on_complete)

    start_time = time.time()

    for p in work_process:
        p.join()

    print("complete all zip @ {0} secs".format(time.time() - start_time))
    # exit(0)  # 615secs 8times 76.875 per time. 74.70 run a time.


# input("Press any key to exit\n")

start_time = 0

if __name__ == "__main__":
    main(sys.argv[1])

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容