題目有點標題黨了:P
測試目標
用 Python 和 Go 的併發編程實現類似 Ansible 的 ping 命令,對比不同併發規模的執行效率。
測試環境
i7 7500 雙核超線程的筆記本,win10系統。
測試結果
主機數 | Ansible | Python multiprocessing | Python threading | Python gevent | Go goroutine |
---|---|---|---|---|---|
10 | 14s | 5s | 0.4s | 0.4s | 120ms |
100 | 34s | MemoryError | 1.5s | 1.5s | 226ms |
1000 | [Errno 24] Too many open files | - | 19s | 19s 偶有連接異常 | 11s |
測試說明
- 我記錄的是多次執行的最快時間,Ansible 尤其不穩定。
- Ansible 運行時間包含了解析 hosts 配置文件的時間,其他程序沒有這個消耗。
測試總結
- 簡單翻了一下 Ansible 的源碼,通過 fork 進程的方式實現並行,並行數量超過 CPU 核數以後 CPU 打滿,性能低,不適合大規模任務執行。
- Python 的多線程和協程效率差不多,資源消耗爲單核打滿。
- Go 的 goroutine 處理大規模併發性能優勢明顯,且 CPU 資源消耗更少,1000 個併發啓動時孵化 goroutine 衝到 40%,很快進入等待I/O狀態,下降到 1%以下。