【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(…...
ColorControl开源显示调校工具:从新手到专家的HDR优化之路
ColorControl开源显示调校工具:从新手到专家的HDR优化之路 【免费下载链接】ColorControl Easily change NVIDIA display settings and/or control LG TVs 项目地址: https://gitcode.com/gh_mirrors/co/ColorControl 在数字显示技术快速发展的今天ÿ…...
BERT自然语言处理模型:从入门到实践完整指南
BERT自然语言处理模型:从入门到实践完整指南 【免费下载链接】bert TensorFlow code and pre-trained models for BERT 项目地址: https://gitcode.com/gh_mirrors/be/bert BERT(Bidirectional Encoder Representations from Transformers&#x…...
Android14 SurfaceFlinger启动流程与线程调度机制解析
1. SurfaceFlinger的启动入口与初始化流程 Android显示系统的核心服务SurfaceFlinger由init进程启动,这个设计保证了它在系统早期就能准备好图形合成能力。main函数作为入口点,首先做了一系列关键初始化: 设置Binder线程池的最大线程数为4&…...
Clover Bootloader虚拟化环境部署终极指南:QEMU、KVM、Xen全平台支持
Clover Bootloader虚拟化环境部署终极指南:QEMU、KVM、Xen全平台支持 【免费下载链接】CloverBootloader Bootloader for macOS, Windows and Linux in UEFI and in legacy mode 项目地址: https://gitcode.com/gh_mirrors/cl/CloverBootloader Clover Bootl…...
WSL2下git clone失败:防火墙与代理配置全解析
1. WSL2下git clone失败的常见现象 最近在WSL2环境下工作时,突然发现git clone命令无法正常拉取远程仓库代码。这个问题困扰了我好几天,经过反复排查才发现是Windows防火墙设置和代理配置的问题。相信很多使用WSL2开发的同行都遇到过类似情况࿱…...
告别答辩夜战!Paperxie AI PPT:10 分钟把论文变「导师满分」学术演示稿
paperxie-免费查重复率aigc检测/开题报告/毕业论文/智能排版/文献综述/AIPPThttps://www.paperxie.cn/ppt/createhttps://www.paperxie.cn/ppt/create 又到毕业季,当实验室的灯光熬到凌晨,当电脑里的论文终稿定格在最后一页,无数毕业生却陷入…...
如何高效管理微信读书笔记:终极免费工具wereader完全指南
如何高效管理微信读书笔记:终极免费工具wereader完全指南 【免费下载链接】wereader 一个功能全面的微信读书笔记助手 wereader 项目地址: https://gitcode.com/gh_mirrors/we/wereader 微信读书助手wereader是一款专为微信读书用户设计的免费开源工具&#…...
繁忙海港水域船舶精细识别与多目标跟踪研究
繁忙海港水域船舶精细识别与多目标跟踪研究 摘要 繁忙海港水域的船舶智能感知是智慧港口与海上交通管理的关键技术。然而,海港场景特有的复杂背景干扰、船舶密集遮挡、相机运动抖动以及小目标检测困难等问题,给船舶的精细化识别与稳定跟踪带来了严峻挑战。本文针对上述问题…...
ATOM-PRINTER嵌入式热敏打印固件深度解析
1. ATOM-PRINTER 嵌入式打印库深度解析与工程实践指南ATOM-PRINTER 是 M5Stack 推出的面向 ESP32 平台的轻量级嵌入式热敏打印固件库,专为 M5Stack Atom 系列微型主控模块(搭载 ESP32-WROVER-B)设计。该库并非传统意义上的“驱动层”C/C 库&a…...
智科毕业设计易上手选题100例
0 选题推荐 - 汇总篇 毕业设计是大家学习生涯的最重要的里程碑,它不仅是对四年所学知识的综合运用,更是展示个人技术能力和创新思维的重要过程。选择一个合适的毕业设计题目至关重要,它应该既能体现你的专业能力,又能满足实际应用…...
