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()
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM