Golang概要分析简单示例,用于培训

I'm doing Go training in my company and I want to present in best way pprof package. I think that My example isn't good enough to simply present power of pprof. I want to use only go std library. Code should give me simplier call graph with some bottleneck.

My current workflow is as below: 1. include pprof in webserver 2. run webserver (it'll gather data for 30 seconds (default)) 3. run some curl shots to webserver 4. present pprof graphs

My code looks like below:

package main

import (
    "fmt"
    "net/http"
    _ "net/http/pprof"
)

func handler(w http.ResponseWriter, r *http.Request) {
    for i := 0; i < 100000000; i++ {
        w.Write([]byte(fmt.Sprintf("%d - %d, ", i, i)))
    }
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Pprof without filtering

ppfof all

Pprof for handler() function only

enter image description here

How about string concatenation? It produces a fairly linear graph on my machine. Besides, this is a good way to teach people why they should build strings by appenting to a []byte rather than concatenating strings, creating tonnes of garbage.

func handler(w http.ResponseWriter, r *http.Request) {
    var s string
    for i := 0; i < 100000; i++ {
        s += strconv.Itoa(i)
    }
    w.Write([]byte(s))
}