golang代码中生成pprof和trace报告

// 生成 CPU 报告
import (
    "context"
    "runtime/pprof"
    "log"    
)

func cpuProfile(ctx context.Context) {
    f, err := os.Create("cpu.prof")
    if err != nil {
        log.Fatal(err)
    }
    log.Println("CPU Profile started")
    pprof.StartCPUProfile(f)
    go func(){
        select{
        case <-ctx.Done():
            pprof.StopCPUProfile()
            f.Close()
        }
    }
 }
// 生成堆内存报告

import (
    "context"
    "runtime/pprof"
    "log"    
)

func heapProfile(ctx context.Context) {
    f, err := os.Create("heap.prof")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    pprof.WriteHeapProfile(f)
    go func(){
        select{
        case <-ctx.Done():
            f.Close()
        }
    }
}

// 生成trace报告
import (
    "context"
    "runtime/trace"
    "log"    
)
func traceProfile(ctx context.Context) {
    f, err := os.OpenFile("trace.out")
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Trace started")
    trace.Start(f)
    go func(){
        select{
        case <-ctx.Done():
            trace.Stop()
            f.Close()
        }
    }
}

posted @ 2019-04-30 19:41  YYRise  阅读(1339)  评论(0编辑  收藏  举报