golang cpu/内存性能分析

本文介绍了如何在Golang中引入pprof库来监控CPU和内存使用情况。通过运行服务、访问特定URL获取pprof数据,然后使用go tool pprof进行分析,包括生成拓扑图和火焰图,帮助开发者快速定位性能瓶颈。此外,还提供了在无法直接访问pprof端口时下载数据的方法。
摘要由CSDN通过智能技术生成

如果cpu或内存占用明显,使用pprof则能很快定位到问题。否则最好结合多个时间段的数据对比进行查看。

1、golang代码中引入pprof

import(
    _ "net/http/pprof"
)

Demo全部代码如下:

package main

import (
	"fmt"
	"log"
	"net/http"
	_ "net/http/pprof"
)

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/hello", helloHandler)
	log.Fatal(http.ListenAndServe(":9999", nil))
}

// handler echoes r.URL.Path
func indexHandler(w http.ResponseWriter, req *http.Request) {
	for i:= 0;i<100;i++ {
		fmt.Fprintf(w, "URL.Path = %q\n", `package main

import (
	"fmt"
	"log"
	"net/http"
	_ "net/http/pprof"
)

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/hello", helloHandler)
	log.Fatal(http.ListenAndServe(":9999", nil))
}

// handler echoes r.URL.Path
func indexHandler(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "URL.Path = %q\n", req.URL.Path)
}

// handler echoes r.URL.Header
func helloHandler(w http.ResponseWriter, req *http.Request) {
	for k, v := range req.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}
}`)
	}
}

// handler echoes r.URL.Header
func helloHandler(w http.ResponseWriter, req *http.Request) {
	for k, v := range req.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}
}

 go run main.go拉起服务

3、浏览器访问

http://localhost:9999/debug/pprof/

 

4、使用pprof

 go tool pprof http://127.0.0.1:9999/debug/pprof/profile

 如下图:

 5、然后我们可以输入命令web,其会给我们的浏览器弹出一个.svg图片,其会把这些累积关系画成一个拓扑图给我们。

如下图 :

此时浏览器会自动访问到svg图片: 

6、或者直接执行

go tool pprof -alloc_space -cum -svg http://192.168.1.17:9999/debug/pprof/heap > heap.svg

或者

go tool pprof -http 0.0.0.0:8899 http://192.168.1.11:32220/debug/pprof/allocs

此时会在本地拉起一个8899的服务,用来实时中转展示服务上pprof上的对应指标

http://192.168.1.17:8899/ui

 通过左上角的菜单栏可以选择看“火焰图’”等等

7、下载数据使用pprof查看(适合不能直接访问到pprof端口的情况,比如容器内)

curl http://xxxxxx/debug/pprof/heap  > base.heap

curl http://xxxxxx/debug/pprof/heap  > current.heap

go tool pprof -http 0.0.0.0:9987 -alloc_space --base base.heap current.heap

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值