對比Python和Go語言的每秒請求數
我使用Python工作已經有幾年了,最近開始了一個關于GO的調查,主要看作是一個緩解瓶頸的實驗,還沒有大規(guī)模web服務器部署。
我用不同語言寫了一個簡單的REST服務,使用ab工具檢測響應速度。
Python
server.py
- from bottle import route, run
- @route('/')
- def home():
- article = {'name': 'A Royal Baby', 'body':'A slow news week'}
- return article
- def main():
- run(host='localhost', port=8081)
- if __name__ == '__main__':
- main()
Go
server.go
- package main
- import (
- "encoding/json"
- "fmt"
- "github.com/emicklei/go-restful"
- "io"
- "net/http"
- )
- func main() {
- ws := new(restful.WebService)
- ws.Route(ws.GET("/").To(hello))
- restful.Add(ws)
- fmt.Print("Server starting on port 8080\n")
- http.ListenAndServe(":8080", nil)
- }
- func hello(req *restful.Request, resp *restful.Response) {
- article := Article{"A Royal Baby", "A slow news week"}
- b, _ := json.Marshal(article)
- io.WriteString(resp, string(b))
- }
- type Article struct {
- Name string
- Body string
- }
Go語言的版本明顯比Python版的更詳細,但我認為它仍然非常言簡意賅。Python服務器使用bottle框架,指定的article字典作為響應自動序列化返回。Go服務器使用go-restful包,這個包使得在Go中很容易構建RESTful API。
測試基準是在Macbook Pro上,CPU i7 2.4Ghz,16GB RAM。
使用下附命令:
ab -q -c 50 -n 1000 http://127.0.0.1:8080/ | grep "Requests per second"
結果
5次測試,1000次請求的平均每秒鐘完成請求次數
Run | Python | Go |
---|---|---|
1 | 1310.58 | 13568.34 |
2 | 1332.82 | 13092.95 |
3 | 1331.54 | 13479.45 |
4 | 1306.09 | 13271.58 |
5 | 1274.49 | 13873.09 |
Go平均完成13457次請求/秒,Python完成1311次請求/秒
在本次測試中,Go在完成JSON響應方面比Python快10.26倍。
我知道這些腳本非常的簡單,而且缺少實際應用中的邏輯——例如數據庫連接。也許有比ab更準確的測試方法,但我認為這些結果足以給你一個嘗試Go的理由。以我目前的經驗,從Python到編譯型語言有很多樂趣。
做過Python/Go基準測試的想一起分享么?
英文原文:Python vs Go - Requests per Second
譯文鏈接:http://www.oschina.net/translate/python-vs-go-requests-per-second