基於 libuv 的 uvloop 令 Python 3.5+ 的 asyncio 更快

By | October 1, 2018

Python 3 已推出一段長時間,文章落筆時最新為 3.7,其間 Python 3 都變了不少,3.6 起基本上已無誘因繼續用 2.7。

PEP 529 — Change Windows filesystem encoding to UTF-8 Windows NT 時用了 UTF-16 支援 Unicode,令 Windows APIs 有一套 9x 帶落 ASCII 的 *A functions (),另一套 UTF16LE 的 *W Functions。Python 3.6 就同 POSIX APIs 睇齊,用 UTF-8,即同 Linux 上一樣,解決好多 cross-platform 檔案存取問題。

PEP 3156 — Asynchronous IO Support Rebooted: the “asyncio” Module / PEP 492 — Coroutines with async and await syntax 重量級元件,asyncio!asyncio 借用了async/await 語法,async/await 在 C# 及 JavaScript 上都可看到其身影,是 non-blocking 的功臣。Node.js 有兩樣野令其聞名於世有,就是 V8 engine 及 non-blocking runtime。

不過 asyncio 依然不及 Node.js 快,於是有了 uvloop。uvloop 是於 libuv,要知道 Node.js 都是基於 libuv 的,這可令 Python 3.5+ 擺脫比 Node.js 慢很多的問題。

uvloop 還不是 Python build-in,要使用 uvloop 需要用 pip install

$ pip install uvloop

import 後用法跟 asyncio 一樣。

import asyncio
import uvloop