@aliasliyu4
2016-11-09T05:50:09.000000Z
字数 1706
阅读 4126
本文的出发点是来自于一次程序的cpu占用异常和内存的飙升,最开始认为这种现象的原因是因为图像在解码和编码的过程中有大量的浮点运算导致的,但是这两者的高占用率在实际的项目当中,对服务器来讲都是难以承受的阿克琉斯之踵。之前在学习go的过程当中,有看到介绍过go的工具链条中有pprof可以用来分析程序的性能,手中有剑,心里就稍微踏实一点。
如果需要分析的程序是web程序,那么你只需要引入_net/http/pprof,大概的伪代码是如下这样的。
web,web,web重要的事情说三遍。
web应用需要引入的代码
package mainimport("log""net/http"_"net/http/pprof")func main() {go func() {//port is you coustom define.log.Println(http.ListenAndServe("localhost:6060", nil))}()//do your stuff.}
以上这段代码加到你的web应用程序,我们就可以用一下的命令去查看一些信息,下面将给出一个完整的代码实例,确保你能够在自己的主机上运行,看得见摸得着总比我干说着要好。
首先我是用beego的bee工具新建了最小的web应用,名字叫pr。
main函数的大概样子。
package mainimport ("github.com/astaxie/beego""log""net/http"_ "net/http/pprof"_ "pr/routers")func main() {go func() {log.Println(http.ListenAndServe("localhost:8081", nil))}()beego.Run()}
执行 go build & ./pr
在浏览器中访问地址: localhost:8081/debug/pprof/pprof/
可以开始愉快的排查问题了。

package mainimport ("flag""fmt""github.com/kevinchen/capture""log""os""runtime/pprof""sync")// var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")var memprofile = flag.String("memprofile", "", "write cpu profile to file")func main() {fmt.Println("test")var wg sync.WaitGroupurl1 := "http://wx.qlogo.cn/mmopen/vi_24/q4uiajQpkzX0yzCJ6Ln4Zzribze3C7k6Z1jmPIIwfqIQAiaqXJqicha9jB3taPLQf9973TZs4pyanibM/0"url2 := "http://wx.qlogo.cn/mmopen/vi_24/gia9TticbVQGYt8GgibGhdpeqOelNUktChwRtRvl9N6YWVnYXNpAm5zibdPOb0P7WE5LUdVz9pqyXwc/0"flag.Parse()if *memprofile != "" {f, err := os.Create(*memprofile)if err != nil {log.Fatal(err)}for i := 0; i < 100; i++ {wg.Add(1)go func() {result, err := capture.CompareResult(url1, url2)pprof.WriteHeapProfile(f)fmt.Println(err)fmt.Println(result)wg.Done()}()}}wg.Wait()}cpu的消耗替换的代码:pprof.StartCPUProfile(f)defer pprof.StopCPUProfile()
运行程序: go tool pprof (application) f
使用web命令生成svg文件。