對(duì)比Python和Go語言的每秒請(qǐng)求數(shù)
我使用Python工作已經(jīng)有幾年了,最近開始了一個(gè)關(guān)于GO的調(diào)查,主要看作是一個(gè)緩解瓶頸的實(shí)驗(yàn),還沒有大規(guī)模web服務(wù)器部署。
我用不同語言寫了一個(gè)簡(jiǎn)單的REST服務(wù),使用ab工具檢測(cè)響應(yīng)速度。
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版的更詳細(xì),但我認(rèn)為它仍然非常言簡(jiǎn)意賅。Python服務(wù)器使用bottle框架,指定的article字典作為響應(yīng)自動(dòng)序列化返回。Go服務(wù)器使用go-restful包,這個(gè)包使得在Go中很容易構(gòu)建RESTful API。
測(cè)試基準(zhǔn)是在Macbook Pro上,CPU i7 2.4Ghz,16GB RAM。
使用下附命令:
ab -q -c 50 -n 1000 http://127.0.0.1:8080/ | grep "Requests per second"
結(jié)果
5次測(cè)試,1000次請(qǐng)求的平均每秒鐘完成請(qǐng)求次數(shù)
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次請(qǐng)求/秒,Python完成1311次請(qǐng)求/秒
在本次測(cè)試中,Go在完成JSON響應(yīng)方面比Python快10.26倍。
我知道這些腳本非常的簡(jiǎn)單,而且缺少實(shí)際應(yīng)用中的邏輯——例如數(shù)據(jù)庫(kù)連接。也許有比ab更準(zhǔn)確的測(cè)試方法,但我認(rèn)為這些結(jié)果足以給你一個(gè)嘗試Go的理由。以我目前的經(jīng)驗(yàn),從Python到編譯型語言有很多樂趣。
做過Python/Go基準(zhǔn)測(cè)試的想一起分享么?
英文原文:Python vs Go - Requests per Second
譯文鏈接:http://www.oschina.net/translate/python-vs-go-requests-per-second