2016-10-06 111 views
0

我正在用fasthttp包构建Rest API。我有我使用来衡量性能的测试路线:Golang fasthttp请求很慢

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这个路径指向的函数就花了那么长时间?

+0

我刚与确切的代码测试,它需要(1秒以下)几乎没有时间在到达'调用println( “HERE”)'。你设置你的测试有多难? –

+0

尝试我的样品和帖子(添加评论)的代码(2)输出 –

回答

2

对于我来说,只需要7.9454545s对于100000 http.Head(79.454545us每http.Head,当运行这些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 - 有了这个优惠:

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 
输出 This code

3-:

8.6294936s