github.com/szq-123/codingpractice@v0.0.0-20240430111904-2778dfaf7994/golang/gotool_test.go (about)

     1  package golang
     2  
     3  import (
     4  	"GolangPractice/utils/logger"
     5  	"net/http"
     6  	"os"
     7  	"runtime/pprof"
     8  	"runtime/trace"
     9  	"testing"
    10  
    11  	_ "net/http/pprof"
    12  )
    13  
    14  /*
    15  	go tool 查看内置工具
    16  
    17  	nm:查看 二进制文件 的符号表(等同于系统 nm 命令)
    18  
    19  	objdump:反汇编工具,分析二进制文件(等同于系统 objdump 命令)
    20  
    21  	cover:生成代码覆盖率
    22  
    23  	compile:代码汇编
    24  		go tool compile -N -l -S example.go 禁用内联和代码优化
    25  		go tool compile -S example.go   查看汇编输出
    26  */
    27  
    28  // runtime.NumGoroutine() 当前协程数量
    29  
    30  // `go tool pprof [pprof_file]` to enter interactive mode.
    31  // use help to get commands you can use, like `top 5`, `list [func_name]`, `png`, etc.
    32  // to visualize profile, install `graphviz` using command like `yum install graphviz`.
    33  // for more at https://go.dev/blog/pprof
    34  func TestRuntimePprof(t *testing.T) {
    35  	// cpu
    36  	f, err := os.Create("cpu.prof")
    37  	if err != nil {
    38  		panic(err)
    39  	}
    40  	defer f.Close()
    41  
    42  	err = pprof.StartCPUProfile(f)
    43  	if err != nil {
    44  		panic(err)
    45  	}
    46  	defer pprof.StopCPUProfile()
    47  
    48  	// 堆内存 pprof.WriteHeapProfile()
    49  }
    50  
    51  // net/http/pprof
    52  func TestNetHttpPprof(t *testing.T) {
    53  	// pprof
    54  	go func() {
    55  		logger.Infoln(http.ListenAndServe(":61111", nil))
    56  	}()
    57  
    58  	// your product code here
    59  	select {}
    60  }
    61  
    62  // trace 采样一段时间,指标跟踪分析工具
    63  func TestTrace(t *testing.T) {
    64  	// 输出信息到pwd/trace.out
    65  	f, err := os.Create("trace.out")
    66  	if err != nil {
    67  		panic(err)
    68  	}
    69  	defer f.Close()
    70  
    71  	err = trace.Start(f)
    72  	if err != nil {
    73  		panic(err)
    74  	}
    75  	defer trace.Stop()
    76  
    77  	// your product code here
    78  	select {}
    79  }