Golang fasthttp请求非常慢

时间:2016-10-06 04:05:50

标签: rest http go fasthttp

我正在使用fasthttp包构建Rest API。我有一个测试路线,用于衡量绩效:

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")
}

如果我向此路线发送请求,则需要10秒钟才能到达测试功能中的println("HERE")

我在Node.js中构建了一个类似的端点,这个完全相同的功能和路由需要126毫秒 为什么在世界上只需要调用此路由在Go中指向的函数需要这么长时间?

1 个答案:

答案 0 :(得分:3)

对我而言,100000 http.Head只需7.9454545(每http.Head 79.454545us,运行这些1和2代码时,只有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

输出:

100000

2-使用此Get:

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.9454545s

3- This code的输出:

8.6294936s