我正在用筋膜包构建Rest。我有一个测试路线,我用它来衡量性能:
package main
import (
"github.com/valyala/fasthttp"
"runtime"
)
func main() {
runtime.GOMAXPROCS(8)
m := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/test":
test(ctx)
default:
ctx.Error("not found", fasthttp.StatusNotFound)
}
}
fasthttp.ListenAndServe(":80", m)
}
func test(ctx *fasthttp.RequestCtx) {
println("HERE")
}如果我向这个路由发送请求,那么在测试函数中到达println("HERE")需要超过10秒。
我已经在Node.js中构建了一个类似的端点,这个完全相同的函数和路由需要126毫秒。
为什么在世界上只需要这么长时间来调用这条路线指向的函数呢?
发布于 2016-10-06 04:33:26
对我来说,100000 http.Head只需要7.94545s(79.4545US/ http.Head,运行这1和2个代码时只有两个核心CPU负载77% )。
您不需要runtime.GOMAXPROCS(8),使用fmt.Println()而不是println()
1-试试:
package main
import (
"fmt"
"github.com/valyala/fasthttp"
)
func main() {
m := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/test":
test(ctx)
default:
fmt.Println(i)
ctx.Error("not found", fasthttp.StatusNotFound)
}
}
fasthttp.ListenAndServe(":80", m)
}
func test(ctx *fasthttp.RequestCtx) {
i++
}
var i int = 0产出:
1000002-用这个得到:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
t := time.Now()
for i := 0; i < 100000; i++ {
read(`http://localhost/test`)
}
fmt.Println(time.Since(t))
read(`http://localhost/`)
}
func read(url string) {
_, err := http.Head(url)
if err != nil {
fmt.Println(err)
}
}产出:
7.9454545s3- 这段代码输出
8.6294936shttps://stackoverflow.com/questions/39887326
复制相似问题