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
協程,異步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 密集型業務包括:瀏覽器交互、磁盤請求、網絡爬蟲、數據庫請求等。
Python 世界對于 IO 密集型場景的并發提升有 3 種方法:多進程、多線程、異步 IO(asyncio)。理論上講asyncio是性能最高的,原因如下:
1.進程、線程會有CPU上下文切換
2.進程、線程需要內核態和用戶態的交互,性能開銷大;而協程對內核透明的,只在用戶態運行
3.進程、線程并不可以無限創建,最佳實踐一般是 CPU*2;而協程并發能力強,并發上限理論上取決于操作系統IO多路復用(Linux下是 epoll)可注冊的文件描述符的極限

下面是一個數據庫訪問的測試:

內存:
串行:75M
多進程:1.4G
多線程:150M
asyncio:120M
以上就是python流水線框架pypeln的安裝使用教程的詳細內容,更多關于python流水線框架的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- Python PyInstaller安裝和使用教程詳解
- windows下Python安裝、使用教程和Notepad++的使用教程
- Python安裝及Pycharm安裝使用教程圖解
- Python 中Django安裝和使用教程詳解
- ubuntu系統下Python虛擬環境的安裝和使用教程
- python的pip安裝以及使用教程
- python入門課程第一講之安裝與優缺點介紹