对于初学者来说,性能分析可能感觉比较高大上,而且不知道应该如何下手。其实,性能分析很简单。只需要简单两步即可完成对go项目进行性能分析。

go项目的性能分析一般分为如下两种:

一种是运行实时监控分析,使用net/http/pprof包,在入口文件main.go中添加对应的端口监听即可


package main

import (
   _"net/http/pprof" 
)

func main(){
   	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		return 
	}
}

运行如上示例,然后在浏览器上访问http://localhost:8080/debug/pprof/即可

另一种是生成对应的pprof文件,使用runtime/pprof包,然后通过浏览器,或者命令行来判断代码逻辑执行过程中主要消耗在哪里。示例如下

package main

import (

   "os"
   "runtime/pprof"
)

func main(){

   file,err:=os.Create("alloc.pprof")
   if err!=nil{
        fmt.println("文件创建失败")
   }
   pprof.StartCPUProfile(file)
   for i:=0;i<10000;i++{
    alloc()  
  }
  pprof.StopCPUProfile()
  file.Close()
}

通过命令行

go tool pprof alloc.pprof

也可以再浏览器上看火焰图

go tool pprof -http=":8080" alloc.pprof

然后打开浏览器访问 http://localhost:8080/ui即可