gpt4 book ai didi

rest - Golang fasthttp 请求很慢

转载 作者:IT王子 更新时间:2023-10-29 01:58:30 26 4
gpt4 key购买 nike

我正在使用 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 中调用这条路由指向的函数就需要这么长时间?

最佳答案

对我来说,100000 个http.Head 只需要 7.9454545s(每个 http.Head 需要 79.454545us,当运行这些 1 时,只有 2 个核心 CPU 在 77% 的负载下和 2 个代码)。

你不需要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- 使用此获取:

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

关于rest - Golang fasthttp 请求很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39887326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com