原因:测试两个多进程的情况下使用 pipe 和 queue 进行通信发送相同数据的时候的性能
# coding=utf-8
import logging
import multiprocessing
import os
import time
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [*] %(processName)s %(message)s"
)
def reader_pipe_test (reader_p):
while True:
try:
msg = reader_p.recv() # 从 pipe 中读取消息
# logging.info(msg) # 最好是注释
except EOFError:
break
def writer_pipe_test (count, writer_p): # 写消息到管道中
for i in range(0, count):
writer_p.send(i) # 发送消息
def reader_queue_test (queue): # 利用队列来发送消息
while True:
msg = queue.get() # 从队列中获取元素
if msg == "DONE":
break
def writer_queue_test (count, queue):
for ii in range(0, count):
queue.put(ii) # 放入消息队列中
queue.put("DONE")
def main (ctx):
logging.info("testing for pipe:--------------------------------")
for count in [10 ** 3, 10 ** 4, 10 ** 5, 10 ** 6]:
_start = time.time()
reader_p, writer_p = ctx.Pipe() # 管道
# 启动读取操作----------------------------------------------------------
reader_pipe = ctx.Process(target=reader_pipe_test, args=((reader_p),))
reader_pipe.start() # 启动进程
reader_p.close() # 读取够了就关闭
# 启动写入操作----------------------------------------------------------
writer_pipe_test(count, writer_p) # 写消息到管道中
writer_p.close() # 写够了就关闭
# 等待子进程处理完毕----------------------------------------------------
reader_pipe.join()
logging.info(f"发送{count}个数据到Pipe() ,花费{time.time() - _start}秒")
logging.info("testsing for queue:------------------------------")
for count in [10 ** 3, 10 ** 4, 10 ** 5, 10 ** 6]:
_start = time.time()
queue = ctx.Queue() # 利用 queue 进行通信
reader_queue = ctx.Process(target=reader_queue_test, args=((queue),))
reader_queue.daemon = True
reader_queue.start()
writer_queue_test(count, queue) # 写消息到 queue 中
reader_queue.join()
logging.info(f"发送{count}个数据到Queue() ,花费{time.time() - _start}秒")
if __name__ == '__main__':
# windows 启动方式
multiprocessing.set_start_method('spawn')
# 获取上下文
ctx = multiprocessing.get_context('spawn')
main(ctx)
输出:从函数输出可以看出,pipe 所消耗的时间较小,性能更好。
2019-10-04 15:18:17,633 [*] MainProcess testing for pipe:--------------------------------
2019-10-04 15:18:17,759 [*] MainProcess 发送1000个数据到Pipe() ,花费0.12518739700317383秒
2019-10-04 15:18:17,935 [*] MainProcess 发送10000个数据到Pipe() ,花费0.17660069465637207秒
2019-10-04 15:18:18,902 [*] MainProcess 发送100000个数据到Pipe() ,花费0.9667224884033203秒
2019-10-04 15:18:28,902 [*] MainProcess 发送1000000个数据到Pipe() ,花费10.000114440917969秒
2019-10-04 15:18:28,902 [*] MainProcess testsing for queue:------------------------------
2019-10-04 15:18:29,010 [*] MainProcess 发送1000个数据到Queue() ,花费0.10828304290771484秒
2019-10-04 15:18:29,295 [*] MainProcess 发送10000个数据到Queue() ,花费0.2847580909729004秒
2019-10-04 15:18:31,040 [*] MainProcess 发送100000个数据到Queue() ,花费1.743804693222046秒
2019-10-04 15:18:43,779 [*] MainProcess 发送1000000个数据到Queue() ,花费12.739366292953491秒