我使用Python工作已经有几年了,最近开始了一个关于GO的调查,主要看作是一个缓解瓶颈的实验,还没有大规模web服务器部署。我用不同语言写了一个简单的REST服务,使用ab工具检测响应速度。
Python server.pyfrom bottle import route, run@route("/")
def home():
article = {"name": "A Royal Baby", "body":"A slow news week"}
return articledef main():
run(host="localhost", port=8081)if __name__ == "__main__":
main()
Go server.go package mainimport (
"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
")
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基准测试的想一起分享么?
相关阅读:Ubuntu 安装Go语言包 http://www.linuxidc.com/Linux/2013-05/85171.htm《Go语言编程》高清完整版电子书 http://www.linuxidc.com/Linux/2013-05/84709.htmGo语言并行之美 -- 超越 “Hello World” http://www.linuxidc.com/Linux/2013-05/83697.htm我为什么喜欢Go语言 http://www.linuxidc.com/Linux/2013-05/84060.htm