github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/main/chapter/ch9_01_tools/file/prof.go (about)

     1  package main
     2  
     3  import (
     4  	"log"
     5  	"math/rand"
     6  	"os"
     7  	"runtime"
     8  	"runtime/pprof"
     9  	"time"
    10  )
    11  
    12  const (
    13  	col = 10000
    14  	row = 10000
    15  )
    16  
    17  func fillMatrix(m *[row][col]int) {
    18  	s := rand.New(rand.NewSource(time.Now().UnixNano()))
    19  
    20  	for i := 0; i < row; i++ {
    21  		for j := 0; j < col; j++ {
    22  			m[i][j] = s.Intn(100000)
    23  		}
    24  	}
    25  }
    26  
    27  func calculate(m *[row][col]int) {
    28  	for i := 0; i < row; i++ {
    29  		tmp := 0
    30  		for j := 0; j < col; j++ {
    31  			tmp += m[i][j]
    32  		}
    33  	}
    34  }
    35  
    36  func main() {
    37  	//创建输出文件
    38  	f, err := os.Create("cpu.prof")
    39  	if err != nil {
    40  		log.Fatal("could not create CPU profile: ", err)
    41  	}
    42  
    43  	// 获取系统信息
    44  	if err := pprof.StartCPUProfile(f); err != nil { //监控cpu
    45  		log.Fatal("could not start CPU profile: ", err)
    46  	}
    47  	defer pprof.StopCPUProfile()
    48  
    49  	// 主逻辑区,进行一些简单的代码运算
    50  	x := [row][col]int{}
    51  	fillMatrix(&x)
    52  	calculate(&x)
    53  
    54  	f1, err := os.Create("mem.prof")
    55  	if err != nil {
    56  		log.Fatal("could not create memory profile: ", err)
    57  	}
    58  	runtime.GC()                                       // GC,获取最新的数据信息
    59  	if err := pprof.WriteHeapProfile(f1); err != nil { // 写入内存信息
    60  		log.Fatal("could not write memory profile: ", err)
    61  	}
    62  	f1.Close()
    63  
    64  	f2, err := os.Create("goroutine.prof")
    65  	if err != nil {
    66  		log.Fatal("could not create groutine profile: ", err)
    67  	}
    68  
    69  	if gProf := pprof.Lookup("goroutine"); gProf == nil {
    70  		log.Fatal("could not write groutine profile: ")
    71  	} else {
    72  		gProf.WriteTo(f2, 0)
    73  	}
    74  	f2.Close()
    75  
    76  }