引入pprof
在代碼庫中引入log和net/http/pprof包缰贝,然后在main入口中起個端口監(jiān)聽
go func() {
log.Println(http.ListenAndServe(":8888", nil))
}()
完整例子代碼
package main
import (
"encoding/binary"
"fmt"
"log"
"net"
"net/http"
_ "net/http/pprof"
"strconv"
"strings"
"time"
)
func main() {
go func() {
log.Println(http.ListenAndServe(":8888", nil))
}()
cidrs := []string{
"1.2.3.4/8",
"1.2.3.4/16",
"1.2.3.4/24",
"1.2.3.4/32",
"1.2.3.4/1",
"1.2.3.4/7",
"1.2.3.4/22",
}
ipInt := [][2]int{
{16777216, 33554431},
{16908288, 16973823},
{16909056, 16909311},
{16909060, 16909060},
{0, 2147483647},
{0, 33554431},
{16908288, 16909311},
}
for {
for times := 0; times < 1000; times++ {
for index := 0; index < len(cidrs); index++ {
cidr := cidrs[index]
targetStart, targetEnd := uint32(ipInt[index][0]), uint32(ipInt[index][1])
start, end, _ := Cidr2range(cidr)
if start != targetStart || end != targetEnd {
fmt.Printf("cidr:%s, targetStart:%d, targetEnd:%d, start:%d, end:%d\n", cidr, targetStart, targetEnd, start, end)
}
}
}
time.Sleep(time.Duration(1) * time.Second)
}
}
// Ip2uint 將ip轉(zhuǎn)換成unit32格式
func Ip2uint(ipStr string) uint32 {
ip := net.ParseIP(ipStr)
if ip == nil {
return 0
}
ip = ip.To4()
return binary.BigEndian.Uint32(ip)
}
// Cidr2range 將cidr格式的ipv4地址轉(zhuǎn)換成[uint32 startIp, uint32 endIp]形式
func Cidr2range(cidr string) (uint32, uint32, error) {
vipSegs := strings.Split(cidr, "/")
ip := Ip2uint(vipSegs[0])
var startIp uint32
var endIp uint32
if len(vipSegs) > 1 {
mask, err := strconv.Atoi(vipSegs[1])
if err != nil {
return 0, 0, fmt.Errorf("mask type conversion failed")
}
startIp = ip & (((1 << uint32(mask)) - 1) << uint32(32-mask))
endIp = ip | ((1 << uint32(32-mask)) - 1)
} else {
startIp = ip
endIp = ip
}
return startIp, endIp, nil
}
在瀏覽器查看
然后在瀏覽器打開http://127.0.0.1:8888/debug/pprof/就能看到數(shù)據(jù)了
通過終端查看
也可以在終端使用go tool 工具查看
go tool pprof http://127.0.0.1:8888/debug/pprof/profile
使用 list 命令查看指定函數(shù)耗時
使用 top n 命令查看耗時最高的n個函數(shù)
通過 graphviz 工具導出 svg 圖查看
(沒有 graphviz 的話桨嫁,在 centos 上可以通過 sudo yum install graphviz 命令下載
執(zhí)行命令 go tool pprof -svg [go 項目編譯的二進制] [prof pb文件, 如pprof.collector.samples.cpu.001.pb] > cpu.svg
然后在瀏覽器中打開 cpu.svg 圖片即可