【go】pprof 性能分析
前言
go pprof
是 Go 语言提供的性能分析工具。它可以帮助开发者分析 Go 程序的性能问题,包括 CPU 使用情况、内存分配情况、阻塞情况等。
主要功能
CPU 性能分析
go pprof
可以对程序的 CPU 使用情况进行分析。它通过在一定时间内对程序的执行进行采样,记录每个函数被调用的次数和执行时间。通过分析这些采样数据,可以确定程序中哪些函数占用了较多的 CPU 时间,从而帮助开发者找到性能瓶颈并进行优化。
例如,使用go tool pprof
命令加上程序的 CPU 性能分析文件,可以启动一个交互式的分析界面。在这个界面中,可以使用各种命令查看不同函数的 CPU 使用情况,如top
命令可以显示占用 CPU 时间最多的函数列表。
内存性能分析
这个工具可以分析程序的内存分配情况。它可以记录程序在运行过程中每个函数分配的内存大小和数量。通过分析这些数据,可以确定程序中哪些函数可能存在内存泄漏或过度分配内存的问题。
例如,使用go tool pprof
命令加上程序的内存性能分析文件,可以查看内存分配的情况。可以使用list
命令查看特定函数的内存分配情况,或者使用web
命令生成一个可视化的内存分配报告。
阻塞分析
go pprof
还可以分析程序中的阻塞情况。它可以检测程序在哪些地方出现了阻塞,如等待锁、通道通信或系统调用等。通过分析阻塞情况,可以帮助开发者找到程序中的并发问题并进行优化。
例如,使用go tool pprof
命令加上程序的阻塞分析文件,可以查看程序中的阻塞情况。可以使用top
命令查看最常见的阻塞点,或者使用list
命令查看特定函数的阻塞情况。
优势
易于使用:
go pprof
是 Go 语言内置的工具,无需安装额外的软件即可使用。它的使用方法相对简单,只需要在程序中添加几行代码就可以生成性能分析文件,然后使用go tool pprof
命令进行分析。
强大的分析功能:
go pprof
提供了丰富的分析功能,可以分析程序的 CPU 使用情况、内存分配情况、阻塞情况等。它还可以生成可视化的报告,帮助开发者更直观地了解程序的性能问题。
与 Go 语言紧密集成:
由于go pprof
是 Go 语言内置的工具,它与 Go 语言的其他工具和库紧密集成。例如,可以使用go test
命令结合-cpuprofile
和-memprofile
参数来生成性能分析文件,方便在测试过程中进行性能分析。
CPU profiling
pprof 使用非常简单。首先调用pprof.StartCPUProfile()
启用 CPU profiling。它接受一个io.Writer类型的参数,pprof会将分析结果写入这个io.Writer
中。为了方便事后分析,我们写到一个文件中。
在要分析的代码后调用pprof.StopCPUProfile()
。那么StartCPUProfile()
和StopCPUProfile()
之间的代码执行情况都会被分析。方便起见可以直接在StartCPUProfile()
后,用defer调用StopCPUProfile()
,即分析这之后的所有代码。
来个普通的demo,后面内存分析也用这段代码
import ("math/rand""os""runtime/pprof""strings""time"
)func generate(n int) []int {nums := make([]int, 0)for i := 0; i < n; i++ {nums = append(nums, rand.Int())}return nums
}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]}}}
}type A struct {b *B
}type B struct {c *C
}type C struct {
}func (a *A) func_a() {a.b.func_b()
}func (b *B) func_b() {b.c.func_c()
}func (c *C) func_c() {nums := generate(10000)bubbleSort(nums)
}
使用 pprof 分析一下运行情况
func main() {f, _ := os.OpenFile("cpu.pprof", os.O_CREATE|os.O_RDWR, 0644)defer f.Close()pprof.StartCPUProfile(f)defer pprof.StopCPUProfile()a := &A{b: &B{c: &C{},},}a.func_a()time.Sleep(time.Second)
}
执行go run main.go
,会生成一个cpu.pprof
文件。这个文件记录了程序的运行状态。使用go tool pprof
命令分析这个文件:
>> go tool pprof cpu.pprof
File: pprof2
Type: cpu
Time: Sep 11, 2024 at 5:40pm (CST)
Duration: 202.37ms, Total samples = 70ms (34.59%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 70ms, 100% of 70ms totalflat flat% sum% cum cum%70ms 100% 100% 70ms 100% main.bubbleSort (inline)0 0% 100% 70ms 100% main.(*A).func_a (inline)0 0% 100% 70ms 100% main.(*B).func_b (inline)0 0% 100% 70ms 100% main.(*C).func_c0 0% 100% 70ms 100% main.main0 0% 100% 70ms 100% runtime.main
(pprof)
list 分析
上面用top命令查看耗时最高的 10 个函数。可以看到bubbleSort
函数耗时最高,累计耗时 70ms,占了总耗时的 100%。我们也可以使用top 5
和top 20
分别查看耗时最高的 5 个 和 20 个函数。
当找到耗时较多的函数,我们还可以使用list命令查看该函数是怎么被调用的,各个调用路径上的耗时是怎样的。list命令后跟一个表示方法名的模式:
(pprof) list bubbleSort
Total: 50ms
ROUTINE ======================== main.bubbleSort in /Users/jasper/work/gitee/test-go/src/pprof/pprof2.go50ms 50ms (flat, cum) 100% of Total. . 58: return nums. . 59:}10ms 10ms 60:func bubbleSort(nums []int) {40ms 40ms 61: for i := 0; i < len(nums); i++ {. . 62: for j := 1; j < len(nums)-i; j++ {. . 63: if nums[j] < nums[j-1] {. . 64: nums[j], nums[j-1] = nums[j-1], nums[j]. . 65: }. . 66: }
(pprof) %
help 查看所有的命令
(pprof) helpCommands:callgrind Outputs a graph in callgrind formatcomments Output all profile commentsdisasm Output assembly listings annotated with samplesdot Outputs a graph in DOT formateog Visualize graph through eogevince Visualize graph through evincegif Outputs a graph image in GIF formatgv Visualize graph through gvkcachegrind Visualize report in KCachegrindlist Output annotated source for functions matching regexppdf Outputs a graph in PDF formatpeek Output callers/callees of functions matching regexppng Outputs a graph image in PNG formatproto Outputs the profile in compressed protobuf formatps Outputs a graph in PS formatraw Outputs a text representation of the raw profilesvg Outputs a graph in SVG formattags Outputs all tags in the profiletext Outputs top entries in text formtop Outputs top entries in text formtopproto Outputs top entries in compressed protobuf formattraces Outputs all profile samples in text formtree Outputs a text rendering of call graphweb Visualize graph through web browserweblist Display annotated source in a web browsero/options List options and their current valuesq/quit/exit/^D Exit pprofOptions:call_tree Create a context-sensitive call treecompact_labels Show minimal headersdivide_by Ratio to divide all samples before visualizationdrop_negative Ignore negative differencesedgefraction Hide edges below <f>*totalfocus Restricts to samples going through a node matching regexphide Skips nodes matching regexpignore Skips paths going through any nodes matching regexpintel_syntax Show assembly in Intel syntaxmean Average sample value over first value (count)nodecount Max number of nodes to shownodefraction Hide nodes below <f>*totalnoinlines Ignore inlines.normalize Scales profile based on the base profile.output Output filename for file-based outputsprune_from Drops any functions below the matched frame.relative_percentages Show percentages relative to focused subgraphsample_index Sample value to report (0-based index or name)show Only show nodes matching regexpshow_from Drops functions above the highest matched frame.source_path Search path for source filestagfocus Restricts to samples with tags in range or matched by regexptaghide Skip tags matching this regexptagignore Discard samples with tags in range or matched by regexptagleaf Adds pseudo stack frames for labels key/value pairs at the callstack leaf.tagroot Adds pseudo stack frames for labels key/value pairs at the callstack root.tagshow Only consider tags matching this regexptrim Honor nodefraction/edgefraction/nodecount defaultstrim_path Path to trim from source paths before searchunit Measurement units to displayOption groups (only set one per group):granularity functions Aggregate at the function level.filefunctions Aggregate at the function level.files Aggregate at the file level.lines Aggregate at the source code line level.addresses Aggregate at the address level.sort cum Sort entries based on cumulative weightflat Sort entries based on own weight: Clear focus/ignore/hide/tagfocus/tagignoretype "help <cmd|option>" for more information
(pprof)
web 模式查看
在浏览器中分析CPU性能数据
go tool pprof -http=:8081 cpu.pprof
火焰图
Memory profiling
上面的CPU分析,内容换成字符串拼接
func (c *C) func_c() {concat(30000)
}const letterBytes = "abcdefghijklmnopqrstuvwxyz"func randomString(n int) string {b := make([]byte, n)for i := range b {b[i] = letterBytes[rand.Intn(len(letterBytes))]}return string(b)
}func concat(n int) string {var s = ""for i := 0; i < n; i++ {s += randomString(100)}return s
}
func main() {f, _ := os.OpenFile("mem.pprof", os.O_CREATE|os.O_RDWR, 0644)defer f.Close()a := &A{b: &B{c: &C{},},}a.func_a()pprof.WriteHeapProfile(f)time.Sleep(time.Second)
}
分析
分析的过程,与上面的CPU部分类似
>> go tool pprof mem.pprof
File: pprof2
Type: inuse_space
Time: Sep 11, 2024 at 5:55pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 674.18kB, 100% of 674.18kB totalflat flat% sum% cum cum%674.18kB 100% 100% 674.18kB 100% main.concat0 0% 100% 674.18kB 100% main.(*A).func_a (inline)0 0% 100% 674.18kB 100% main.(*B).func_b (inline)0 0% 100% 674.18kB 100% main.(*C).func_c (inline)0 0% 100% 674.18kB 100% main.main0 0% 100% 674.18kB 100% runtime.main
(pprof) list concat
Total: 674.18kB
ROUTINE ======================== main.concat in /Users/jasper/work/gitee/test-go/src/pprof/pprof2.go674.18kB 674.18kB (flat, cum) 100% of Total. . 46:func concat(n int) string {. . 47: var s = "". . 48: for i := 0; i < n; i++ {674.18kB 674.18kB 49: s += randomString(100). . 50: }. . 51: return s. . 52:}. . 53:. . 54:func generate(n int) []int {
(pprof)
用+
做字符串拼接是很耗内存的,各位可以试着用strings.Builder
,然后观察内存占用的变化。
web 模式查看
在浏览器中分析CPU性能数据
go tool pprof -http=:8081 mem.pprof
相关文章:

【go】pprof 性能分析
前言 go pprof是 Go 语言提供的性能分析工具。它可以帮助开发者分析 Go 程序的性能问题,包括 CPU 使用情况、内存分配情况、阻塞情况等。 主要功能 CPU 性能分析 go pprof可以对程序的 CPU 使用情况进行分析。它通过在一定时间内对程序的执行进行采样࿰…...

Python | Leetcode Python题解之第397题整数替换
题目: 题解: class Solution:def integerReplacement(self, n: int) -> int:ans 0while n ! 1:if n % 2 0:ans 1n // 2elif n % 4 1:ans 2n // 2else:if n 3:ans 2n 1else:ans 2n n // 2 1return ans...

JDBC使用
7.2 创建JDBC应用 7.2.1 创建JDBC应用程序的步骤 使用JDBC操作数据库中的数据包括6个基本操作步骤: (1)载入JDBC驱动程序: 首先要在应用程序中加载驱动程序driver,使用Class.forName()方法加载特定的驱动程序…...
633. 平方数之和-LeetCode(C++)
633. 平方数之和 2024.9.11 题目 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 b2 c 。 0 < c < 2的31次方 - 1 示例 示例 1: 输入:c 5 输出:true 解释:1 * 1 2 * 2 5示…...

Linux shell编程学习笔记79:cpio命令——文件和目录归档工具(下)
在 Linux shell编程学习笔记78:cpio命令——文件和目录归档工具(上)-CSDN博客https://blog.csdn.net/Purpleendurer/article/details/142095476?spm1001.2014.3001.5501中,我们研究了 cpio命令 的功能、格式、选项说明 以及 cpi…...
《 C++ 修炼全景指南:七 》优先级队列在行动:解密 C++ priority_queue 的实现与应用
1、引言 在现代编程中,处理动态优先级队列的需求随处可见,例如任务调度、路径规划、数据压缩等应用场景都依赖于高效的优先级管理。C 标准库提供了 priority_queue 这一强大的工具,它的独特之处在于它的排序特性,priority_queue …...

通信工程学习:什么是HSS归属用户服务器
HSS:归属用户服务器 HSS(归属用户服务器,Home Subscriber Server)是IP多媒体子系统(IMS)中控制层的一个重要组成部分,它扮演着存储和管理用户相关信息的核心角色。以下是关于HSS归属用户服务器的…...
mysql workbench 如何访问远程数据库
要使用 MySQL Workbench 访问远程数据库,可以按照以下步骤操作: 步骤 1:获取远程数据库的连接信息 首先,确保你有远程数据库的以下信息: 主机名(Host):通常是服务器的 IP 地址或域…...

ICMAN触摸感应芯片方案
ICMAN触摸感应芯片 ICMAN触摸感应芯片采用先进的电容感应技术,能够精确检测和识别触摸动作。这一技术通过感应人体与传感器之间的微小电容变化来实现触控功能。相比传统的电阻式触控技术,电容感应技术具有更高的灵敏度和响应速度,能够提供更…...
面向个小微型企业的开源大模型(Qwen2等)商业化, AI部署成本分析与优化策略(费用分析、资源消耗分析)
小微企业AI大模型部署服务器解决方案:资源及成本分析 1.GPU-LLM技术依赖评估依据 在当前全球化的背景下,本地化需求日益凸显,无论是企业拓展国际市场还是个人用户追求更加贴近本土化的服务体验,都对技术的本地化部署提出了更高要求。随着人工智能(AI)技术的飞速发展,尤…...
pandas判断一列中存在nan值
pandas判断一列中存在nan值 在使用 pandas 时,判断一列是否存在 NaN 值可以通过多种方法完成。以下是几种常用的方法: 使用 isna() 和 any() 方法 import pandas as pd import numpy as np# 创建示例数据 df = pd.DataFrame({A: [...

如何将 Electron 项目上架 Apple Store
前言 Electron 是一个开源框架,它允许开发者使用 Web 技术(HTML、CSS 和 JavaScript)来构建跨平台的桌面应用程序。 Electron 应用程序可以运行在 Windows、macOS 和 Linux 上,为用户提供了一种统一的方式来开发和维护软件。 本文将探讨如何将 Electron 构建的桌面应用程…...

R语言统计分析——功效分析2(t检验,ANOVA)
参考资料:R语言实战【第2版】 1、t检验 对于t检验,pwr.t.test()函数提供了许多有用的功效分析选项,如下: pwr.t.test(n,d,sig.level,power,type,alternative) 其中,n为样本大小; d为效应值,即…...
android 侧滑返回上一界面备忘
ParfoisMeng/SlideBack: 无需继承的Activity侧滑返回库 类全面屏返回手势效果 仿“即刻”侧滑返回 (github.com)...
golang学习笔记18——golang 访问 mysql 数据库全解析
推荐学习文档 golang应用级os框架,欢迎star基于golang开发的一款超有个性的旅游计划app经历golang实战大纲golang优秀开发常用开源库汇总golang学习笔记01——基本数据类型golang学习笔记02——gin框架及基本原理golang学习笔记03——gin框架的核心数据结构golang学…...
苹果账号登录后端验证两种方式 python2
import time import jwt import requests import json import base64def decode_jwt(jwt_token):try:h,p,s jwt_token.split(.)except:return {},{},{},"","",""header json.loads(base64.urlsafe_b64decode(h )) # 可能需要调整填充pa…...

FlinkCDC 3.2.0 新增优点 Pattern Replacement in routing rules
新增优点:Pattern Replacement in routing rules flinkcdc 3.2.0版本相较于3.1.0版本,避免了多表多sink多次写 route 路由的麻烦,类似于统一前后缀的形式多表多sink,通过<>正则,大大减少了书写 官网࿱…...

《 C++ 修炼全景指南:六 》深入探索 C++ 标准库中的 stack 与 queue 容器适配器
1、引言 1.1、容器适配器的概念与应用 容器适配器(Container Adapters)是 C 标准库提供的一种特殊容器,它不是一种独立的容器,而是对其他标准容器的封装,用来实现特定的数据结构如栈(stack)和…...
高级java每日一道面试题-2024年9月07日-JVM篇-说一下类加载的执行过程?
如果有遗漏,评论区告诉我进行补充 面试官: 说一下类加载的执行过程? 我回答: 在Java中,类的加载是一个重要的过程,它是由Java虚拟机(JVM)的类加载器系统负责的。类加载的过程不仅仅包括加载类的字节码到内存中,还包…...
笔试强训day09
添加逗号 import sysa list(input())[::-1] s "" cnt 0 for v in a:cnt 1s vif cnt%30:s , print(s.rstrip(,)[::-1])跳台阶 import sys import functools functools.cache def dfs(u):if u1 or u2:# print(f"u {u}")return ureturn dfs(u-1)dfs(…...
Vim 调用外部命令学习笔记
Vim 外部命令集成完全指南 文章目录 Vim 外部命令集成完全指南核心概念理解命令语法解析语法对比 常用外部命令详解文本排序与去重文本筛选与搜索高级 grep 搜索技巧文本替换与编辑字符处理高级文本处理编程语言处理其他实用命令 范围操作示例指定行范围处理复合命令示例 实用技…...
[2025CVPR]DeepVideo-R1:基于难度感知回归GRPO的视频强化微调框架详解
突破视频大语言模型推理瓶颈,在多个视频基准上实现SOTA性能 一、核心问题与创新亮点 1.1 GRPO在视频任务中的两大挑战 安全措施依赖问题 GRPO使用min和clip函数限制策略更新幅度,导致: 梯度抑制:当新旧策略差异过大时梯度消失收敛困难:策略无法充分优化# 传统GRPO的梯…...
Android Wi-Fi 连接失败日志分析
1. Android wifi 关键日志总结 (1) Wi-Fi 断开 (CTRL-EVENT-DISCONNECTED reason3) 日志相关部分: 06-05 10:48:40.987 943 943 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid44:9b:c1:57:a8:90 reason3 locally_generated1解析: CTR…...

遍历 Map 类型集合的方法汇总
1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

大型活动交通拥堵治理的视觉算法应用
大型活动下智慧交通的视觉分析应用 一、背景与挑战 大型活动(如演唱会、马拉松赛事、高考中考等)期间,城市交通面临瞬时人流车流激增、传统摄像头模糊、交通拥堵识别滞后等问题。以演唱会为例,暖城商圈曾因观众集中离场导致周边…...
生成 Git SSH 证书
🔑 1. 生成 SSH 密钥对 在终端(Windows 使用 Git Bash,Mac/Linux 使用 Terminal)执行命令: ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" 参数说明: -t rsa&#x…...

2025 后端自学UNIAPP【项目实战:旅游项目】6、我的收藏页面
代码框架视图 1、先添加一个获取收藏景点的列表请求 【在文件my_api.js文件中添加】 // 引入公共的请求封装 import http from ./my_http.js// 登录接口(适配服务端返回 Token) export const login async (code, avatar) > {const res await http…...

Mac软件卸载指南,简单易懂!
刚和Adobe分手,它却总在Library里给你写"回忆录"?卸载的Final Cut Pro像电子幽灵般阴魂不散?总是会有残留文件,别慌!这份Mac软件卸载指南,将用最硬核的方式教你"数字分手术"࿰…...

Psychopy音频的使用
Psychopy音频的使用 本文主要解决以下问题: 指定音频引擎与设备;播放音频文件 本文所使用的环境: Python3.10 numpy2.2.6 psychopy2025.1.1 psychtoolbox3.0.19.14 一、音频配置 Psychopy文档链接为Sound - for audio playback — Psy…...
HTML前端开发:JavaScript 常用事件详解
作为前端开发的核心,JavaScript 事件是用户与网页交互的基础。以下是常见事件的详细说明和用法示例: 1. onclick - 点击事件 当元素被单击时触发(左键点击) button.onclick function() {alert("按钮被点击了!&…...