golang pprof 性能分析工具

Go pprof 性能分析工具指南

1. 概述

本文档系统介绍了 Go 语言中 pprof 性能分析工具的使用方法,重点分析不同 profiling 工具(goroutine、profile、heap 等)的适用场景,帮助开发者针对性地选择性能分析工具。

2. 各工具使用场景

2.1 Goroutine 分析

适用场景
  • goroutine 泄漏检测:程序运行中 goroutine 数量持续增长不下降
  • 阻塞问题排查:怀疑存在 goroutine 阻塞或死锁问题
  • 并发模型分析:需要了解程序并发模型和 goroutine 分布情况
  • 高并发调优:高并发场景下的性能问题排查

代码示例:

package main

import (
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"sync"
	"time"
)

func main() {
	// 启动 pprof 服务
	go func() {
		fmt.Println("pprof 服务地址: http://localhost:6060/debug/pprof")
		http.ListenAndServe("localhost:6060", nil)
	}()

	// 场景1: channel 接收阻塞
	ch1 := make(chan int)
	go func() {
		fmt.Println("channel 阻塞 goroutine 启动")
		<-ch1 // 永久阻塞
	}()

	go func() {
		time.Sleep(2 * time.Minute)
		fmt.Println("2分钟后解除 channel 阻塞")
		ch1 <- 1
	}()

	// 场景2: select 多路等待
	go func() {
		ch1 := make(chan int)
		ch2 := make(chan int)

		fmt.Println("select 多路等待 goroutine 启动")
		select {
		case <-ch1:
		case <-ch2:
		}
	}()

	// 场景3: 锁竞争
	go func() {
		var mu sync.Mutex
		mu.Lock() // 获取锁

		go func() {
			time.Sleep(time.Minute)
			fmt.Println("1分钟后解锁")
			mu.Unlock()
		}()
		
		fmt.Println("锁竞争 goroutine 启动")
		mu.Lock() // 再次获取锁导致阻塞
	}()

	fmt.Println("程序运行中,查看 goroutine 状态方法:")
	fmt.Println("1. 浏览器访问: http://localhost:6060/debug/pprof/goroutine?debug=1")
	fmt.Println("2. 命令行: go tool pprof http://localhost:6060/debug/pprof/goroutine")
	fmt.Println("程序将在 5 分钟后退出...")

	time.Sleep(5 * time.Minute)
	fmt.Println("程序退出")
}

运行观察:

数据采集方式

通过 HTTP 接口采集

以下两种方案均可:

  • go tool pprof -http=:8080 http://localhost:6060/debug/goroutine
  • http://localhost:6060/debug/pprof/goroutine

通过程序运行时采集

import _ “net/http/pprof”

  • 初始状态:

    • 程序启动初期存在 sync.Mutex.Lock 和 channel 阻塞:初期状态channel接收
  • 1分钟后(锁释放):
    解锁状态阻塞消失

  • 2分钟后(channel 解除阻塞):

    2分钟后状态
    解除阻塞

持续更新…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值