go tool pprof 使用

package main

import "sync"
import "time"
import "fmt"
import (
	"runtime"
	"runtime/debug"
	"runtime/pprof"
	"os"
	"strings"
	"strconv"
)

type myLocker sync.Locker
var (
	progname string
)

func init() {
	paths := strings.Split(os.Args[0], "/")
	paths = strings.Split(paths[len(paths)-1], string(os.PathSeparator))
	progname = paths[len(paths)-1]
	fmt.Println("progname:", progname)
	runtime.MemProfileRate = 1
}

func main() {
	var lock myLocker = new(sync.Mutex)
	lock.Lock()
	lock.Unlock()
	defer func(){
		fmt.Println("defer 1")
		duration := time.Duration(300)*time.Second
		time.Sleep(duration)
	}()
	defer func() {
		fmt.Println("defer 2")
		if err := recover(); err != nil{
			fmt.Println("recover err:", err)
			fmt.Println(string(debug.Stack()))
			duration := time.Duration(10)*time.Second
			time.Sleep(duration)
		}
	}()
	defer saveHeapProfile()
	
	for i := 0; i < 10; i++ {
        go gofunc()
	}
	
	var mm = make(map[int]string)
	mm[1] = "jfskjkfs"
}

func gofunc() {
    fmt.Println("gofunc...")
    for {
	    time.Sleep(time.Duration(8)*time.Second)
	}
}

func saveHeapProfile() {
	runtime.GC()
	//f, err := os.Create(fmt.Sprintf("prof/heap_%s_%d_%s.prof", progname, pid, time.Now().Format("2006_01_02_03_04_05")))
	//f, err := os.Create(fmt.Sprintf("heap_%s_%s.prof", progname, time.Now().Format("2006_01_02_03_04_05")))
	f, err := os.Create(progname+".prof")
	if err != nil {
		return
	}
	defer f.Close()
	//pprof.Lookup("heap").WriteTo(f, 1)
	pprof.WriteHeapProfile(f)
}

生成prof文件后,使用 go tool pprof (应用程序) (prof文件) 方式来对这个 prof 文件进行分析

go tool pprof test test.prof,结果如下图:

go tool pprof 使用_第1张图片

 

 

你可能感兴趣的:(GOLANG)