Golang大杀器之pprof
需要下载graphviz
package main
import (
"math/rand"
"os"
"runtime/pprof"
"time"
)
func generate(n int) []int {
rand.Seed(time.Now().UnixNano())
nums := make([]int, 0)
for i := 0; i < n; i++ {
nums = append(nums, rand.Int())
}
return nums
}
// bubbleSort 冒泡排序。
func bubbleSort(nums []int) {
for i := 0; i < len(nums); i++ {
for j := 1; j < len(nums)-i; j++ {
if nums[j] < nums[j-1] {
nums[j], nums[j-1] = nums[j-1], nums[j]
}
}
}
}
func main() {
f, _ := os.OpenFile("cpu.pprof", os.O_CREATE|os.O_RDWR, 0644)
defer f.Close()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
n := 10
for i := 0; i < 5; i++ {
nums := generate(n)
bubbleSort(nums)
n *= 10
}
}
go run main.go
go tool pprof -http=:9999 cpu.pprof
基于gin框架封装好的包 https://github.com/gin-contrib/pprof
或者结合gin框架,线上起一个协程,时时监控
package main
import (
"github.com/gin-gonic/gin"
"net/http"
_ "net/http/pprof" // 导入 pprof 包
)
func main() {
// 创建一个 Gin 路由器
router := gin.Default()
// 注册 Gin 的路由
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})
// 设置 pprof 的路由,通常放在 /pprof 下
go func() {
// 启动一个 HTTP 服务来处理 pprof 请求
// 注意:在生产环境中,你可能需要使用更安全的机制来暴露这些端点
http.ListenAndServe(":6060", nil)
}()
// 启动 Gin 服务器
router.Run()
}
http://localhost:6060/debug/pprof/ - 显示所有可用的 pprof 端点
http://localhost:6060/debug/pprof/profile - 获取 CPU 分析数据
http://localhost:6060/debug/pprof/heap - 获取内存分析数据
http://localhost:6060/debug/pprof/goroutine - 获取 goroutine 列表
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)