pprof 配置文件与 julienschmidtrouter 和基准测试不分析处理程序

pprof profile with julienschmidtrouter and benchmarks not profiling handler

我正在尝试分析我编写的 Web 服务器,但我的 pprof 不包含有关处理程序函数的任何数据。
我正在使用 httprouter package by julienschmidt, and want to simply benchmark one of my handlers and see the pprof profile for that. For the benchmarking, I am using go-wrk

我这样设置我的网络服务器和 pprof:

// Configure the server
server := &http.Server{
    Addr:    ":4000",
    Handler: router,
}

go func() {
    log.Println(http.ListenAndServe(":6060", nil))
}()

// Start the server
err = server.ListenAndServe()
if err != nil {
    panic(err)
}

路由器初始化如下:

// Create the httprouter
router := httprouter.New()
// Register all handlers
router.GET("/entities/:type/map", h.UseHandler(&h.ApiGetEntitiesMapRequest{}, p))

我的处理程序如下所示:

func (req ApiGetEntitiesMapRequest) Handle(r *http.Request, hrp httprouter.Params, p Params) (interface{}, error) {
    test := make([]string, 0)
    for i := 0; i < 1000; i++ {
        test = append(test, "1")
        test = append(test, "2")
        // Ensure pprof has some time to collect its data
        time.Sleep(10)
    }
    return test, nil
}

这个处理程序只是一个测试,我在其中动态地将很多元素附加到一个切片中。这样做的原因是,我想测试这些动态分配是否在 pprof 的堆配置文件中表示。

现在,我所做的是:

请求有效,我的基准测试也正确报告了所有内容。但是,当我在 pprof 终端中键入 png 时,我得到了这张图 .

该图不包含有关我的处理程序和我在处理程序中进行的代价高昂的堆分配的任何信息。我做错了什么?

所以,我终于找到问题了!

如果您使用自定义 mux 来处理您的请求,您需要将 pprof 处理程序注册到您的 mux,以便获得正确的分析:

router.HandlerFunc(http.MethodGet, "/debug/pprof/", pprof.Index)
router.HandlerFunc(http.MethodGet, "/debug/pprof/cmdline", pprof.Cmdline)
router.HandlerFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
router.HandlerFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
router.HandlerFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
router.Handler(http.MethodGet, "/debug/pprof/goroutine", pprof.Handler("goroutine"))
router.Handler(http.MethodGet, "/debug/pprof/heap", pprof.Handler("heap"))
router.Handler(http.MethodGet,"/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
router.Handler(http.MethodGet,"/debug/pprof/block", pprof.Handler("block"))

现在我得到了我想要的结果!