python流水線框架pypeln的安裝使用教程
1. 安裝和入門使用
安裝pip install pypeln
,基本元素如下:
2 基于multiprocessing.Process
這個是基于多進程。
import pypeln as pl import time from random import random def slow_add1(x): time.sleep(random()) # <= some slow computation return x + 1 def slow_gt3(x): time.sleep(random()) # <= some slow computation return x > 3 data = range(10) # [0, 1, 2, ..., 9] stage = pl.process.map(slow_add1, data, workers=3, maxsize=4) stage = pl.process.filter(slow_gt3, stage, workers=2) data = list(stage) # e.g. [5, 6, 9, 4, 8, 10, 7]
3 基于threading.Thread
顧名思義,基于多線程。
import pypeln as pl import time from random import random def slow_add1(x): time.sleep(random()) # <= some slow computation return x + 1 def slow_gt3(x): time.sleep(random()) # <= some slow computation return x > 3 data = range(10) # [0, 1, 2, ..., 9] stage = pl.thread.map(slow_add1, data, workers=3, maxsize=4) stage = pl.thread.filter(slow_gt3, stage, workers=2) data = list(stage) # e.g. [5, 6, 9, 4, 8, 10, 7]
4 基于asyncio.Task
協(xié)程,異步io。
import pypeln as pl import asyncio from random import random async def slow_add1(x): await asyncio.sleep(random()) # <= some slow computation return x + 1 async def slow_gt3(x): await asyncio.sleep(random()) # <= some slow computation return x > 3 data = range(10) # [0, 1, 2, ..., 9] stage = pl.task.map(slow_add1, data, workers=3, maxsize=4) stage = pl.task.filter(slow_gt3, stage, workers=2) data = list(stage) # e.g. [5, 6, 9, 4, 8, 10, 7]
5 三者性能對比
IO 密集型應用CPU等待IO時間遠大于CPU 自身運行時間,太浪費;常見的 IO 密集型業(yè)務包括:瀏覽器交互、磁盤請求、網絡爬蟲、數據庫請求等。
Python 世界對于 IO 密集型場景的并發(fā)提升有 3 種方法:多進程、多線程、異步 IO(asyncio)。理論上講asyncio是性能最高的,原因如下:
1.進程、線程會有CPU上下文切換
2.進程、線程需要內核態(tài)和用戶態(tài)的交互,性能開銷大;而協(xié)程對內核透明的,只在用戶態(tài)運行
3.進程、線程并不可以無限創(chuàng)建,最佳實踐一般是 CPU*2;而協(xié)程并發(fā)能力強,并發(fā)上限理論上取決于操作系統(tǒng)IO多路復用(Linux下是 epoll)可注冊的文件描述符的極限
下面是一個數據庫訪問的測試:
內存:
串行:75M
多進程:1.4G
多線程:150M
asyncio:120M
以上就是python流水線框架pypeln的安裝使用教程的詳細內容,更多關于python流水線框架的資料請關注腳本之家其它相關文章!
相關文章
在Linux上安裝Python的Flask框架和創(chuàng)建第一個app實例的教程
這篇文章主要介紹了在Linux上安裝Python的Flask框架和創(chuàng)建第一個app實例,包括創(chuàng)建一個HTML模版和利用Jinja2模板引擎來做渲染的步驟,需要的朋友可以參考下2015-03-03