当前位置: 首页 > news >正文

【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 5top 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

image

火焰图
image

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 程序的性能问题&#xff0c;包括 CPU 使用情况、内存分配情况、阻塞情况等。 主要功能 CPU 性能分析 go pprof可以对程序的 CPU 使用情况进行分析。它通过在一定时间内对程序的执行进行采样&#xff0…...

Python | Leetcode Python题解之第397题整数替换

题目&#xff1a; 题解&#xff1a; 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个基本操作步骤&#xff1a; &#xff08;1&#xff09;载入JDBC驱动程序&#xff1a; 首先要在应用程序中加载驱动程序driver&#xff0c;使用Class.forName()方法加载特定的驱动程序&#xf…...

633. 平方数之和-LeetCode(C++)

633. 平方数之和 2024.9.11 题目 给定一个非负整数 c &#xff0c;你要判断是否存在两个整数 a 和 b&#xff0c;使得 a2 b2 c 。 0 < c < 2的31次方 - 1 示例 示例 1&#xff1a; 输入&#xff1a;c 5 输出&#xff1a;true 解释&#xff1a;1 * 1 2 * 2 5示…...

Linux shell编程学习笔记79:cpio命令——文件和目录归档工具(下)

在 Linux shell编程学习笔记78&#xff1a;cpio命令——文件和目录归档工具&#xff08;上&#xff09;-CSDN博客https://blog.csdn.net/Purpleendurer/article/details/142095476?spm1001.2014.3001.5501中&#xff0c;我们研究了 cpio命令 的功能、格式、选项说明 以及 cpi…...

《 C++ 修炼全景指南:七 》优先级队列在行动:解密 C++ priority_queue 的实现与应用

1、引言 在现代编程中&#xff0c;处理动态优先级队列的需求随处可见&#xff0c;例如任务调度、路径规划、数据压缩等应用场景都依赖于高效的优先级管理。C 标准库提供了 priority_queue 这一强大的工具&#xff0c;它的独特之处在于它的排序特性&#xff0c;priority_queue …...

通信工程学习:什么是HSS归属用户服务器

HSS&#xff1a;归属用户服务器 HSS&#xff08;归属用户服务器&#xff0c;Home Subscriber Server&#xff09;是IP多媒体子系统&#xff08;IMS&#xff09;中控制层的一个重要组成部分&#xff0c;它扮演着存储和管理用户相关信息的核心角色。以下是关于HSS归属用户服务器的…...

mysql workbench 如何访问远程数据库

要使用 MySQL Workbench 访问远程数据库&#xff0c;可以按照以下步骤操作&#xff1a; 步骤 1&#xff1a;获取远程数据库的连接信息 首先&#xff0c;确保你有远程数据库的以下信息&#xff1a; 主机名&#xff08;Host&#xff09;&#xff1a;通常是服务器的 IP 地址或域…...

ICMAN触摸感应芯片方案

ICMAN触摸感应芯片 ICMAN触摸感应芯片采用先进的电容感应技术&#xff0c;能够精确检测和识别触摸动作。这一技术通过感应人体与传感器之间的微小电容变化来实现触控功能。相比传统的电阻式触控技术&#xff0c;电容感应技术具有更高的灵敏度和响应速度&#xff0c;能够提供更…...

面向个小微型企业的开源大模型(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)

参考资料&#xff1a;R语言实战【第2版】 1、t检验 对于t检验&#xff0c;pwr.t.test()函数提供了许多有用的功效分析选项&#xff0c;如下&#xff1a; pwr.t.test(n,d,sig.level,power,type,alternative) 其中&#xff0c;n为样本大小&#xff1b; d为效应值&#xff0c;即…...

android 侧滑返回上一界面备忘

ParfoisMeng/SlideBack: 无需继承的Activity侧滑返回库 类全面屏返回手势效果 仿“即刻”侧滑返回 (github.com)...

golang学习笔记18——golang 访问 mysql 数据库全解析

推荐学习文档 golang应用级os框架&#xff0c;欢迎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

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

《 C++ 修炼全景指南:六 》深入探索 C++ 标准库中的 stack 与 queue 容器适配器

1、引言 1.1、容器适配器的概念与应用 容器适配器&#xff08;Container Adapters&#xff09;是 C 标准库提供的一种特殊容器&#xff0c;它不是一种独立的容器&#xff0c;而是对其他标准容器的封装&#xff0c;用来实现特定的数据结构如栈&#xff08;stack&#xff09;和…...

高级java每日一道面试题-2024年9月07日-JVM篇-说一下类加载的执行过程?

如果有遗漏,评论区告诉我进行补充 面试官: 说一下类加载的执行过程? 我回答: 在Java中&#xff0c;类的加载是一个重要的过程&#xff0c;它是由Java虚拟机&#xff08;JVM&#xff09;的类加载器系统负责的。类加载的过程不仅仅包括加载类的字节码到内存中&#xff0c;还包…...

笔试强训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(…...

华尔街量化团队内部文档流出(Perplexity财经数据查询SOP v2.3):含12类高频Query模板+错误码速查表

更多请点击&#xff1a; https://codechina.net 第一章&#xff1a;Perplexity财经数据查询概述 Perplexity 是一款基于大语言模型的智能搜索与知识发现工具&#xff0c;其在财经领域展现出独特优势&#xff1a;它能实时整合权威信源&#xff08;如 SEC、Bloomberg、Reuters、…...

Perplexity图标搜索效率提升300%:从零配置到精准获取的5步实战工作流

更多请点击&#xff1a; https://kaifayun.com 第一章&#xff1a;Perplexity图标资源搜索 在构建与 Perplexity AI 集成的前端应用或开发调试工具时&#xff0c;获取其官方图标资源是品牌一致性与用户体验的关键环节。Perplexity 官方未提供公开的图标下载中心&#xff0c;但…...

【JPCS出版、EI检索稳定】2026年航空航天工程与空天信息国际学术会议(ICAEAI 2026)

2026年航空航天工程与空天信息国际学术会议&#xff08;ICAEAI 2026&#xff09;将于2026年6月26-28日在哈尔滨召开。会议旨在为从事航空航天工程与空天信息领域研究的专家学者、工程技术人员、技术研发人员提供一个共享科研成果和前沿技术&#xff0c;加强学术研究和探讨&…...

食品制造 | 品控AI自动化方案主流厂商横评:2026企业级智能体选型与落地实测

2026年&#xff0c;全球食品制造业正处于从“数字化转型”向“智能化深耕”跨越的关键节点。随着国家市场监管总局“互联网AI监管”战略的全面深化&#xff0c;食品安全已不再仅仅依赖于周期性的线下抽检&#xff0c;而是转向了基于AI技术的全时段、全链路实时监控。 从校园食堂…...

GX Works3实战:基于TCP+SLMP协议与三菱FX5U的工业互联配置详解

1. 从零开始搭建FX5U通信环境 第一次接触三菱FX5U系列PLC时&#xff0c;我被它小巧的机身和强大的性能惊艳到了。这款PLC虽然体积只有传统Q系列的一半大小&#xff0c;但处理能力却提升了两倍以上。不过在实际项目中&#xff0c;最让我头疼的就是通信配置问题——特别是从老项…...

银河麒麟系统下Qt5.9.9编译fcitx-qt5的版本适配与源码修改实战

1. 银河麒麟系统下Qt中文输入问题的根源 在银河麒麟系统上开发Qt应用程序时&#xff0c;中文输入法无法正常切换是个常见痛点。这个问题本质上源于Qt输入法插件与Qt版本之间的兼容性断裂。我曾在多个项目中遇到这种情况&#xff1a;明明系统自带输入法可以正常工作&#xff0c;…...

Typora LaTeX主题:学术论文写作的终极解决方案

Typora LaTeX主题&#xff1a;学术论文写作的终极解决方案 【免费下载链接】typora-latex-theme 将Typora伪装成LaTeX的中文样式主题&#xff0c;本科生轻量级课程论文撰写的好帮手。This is a theme disguising Typora into Chinese LaTeX style. 项目地址: https://gitcode…...

长期项目使用Taotoken Token Plan套餐的成本控制实际体验

&#x1f680; 告别海外账号与网络限制&#xff01;稳定直连全球优质大模型&#xff0c;限时半价接入中。 &#x1f449; 点击领取海量免费额度 长期项目使用Taotoken Token Plan套餐的成本控制实际体验 1. 项目背景与成本挑战 在为期数月的AI应用开发项目中&#xff0c;我们…...

医疗设备晶振精度:从ppm偏差到诊断治疗安全的关键影响

1. 项目概述&#xff1a;从一颗“心跳”说起在医疗设备这个对可靠性要求近乎苛刻的领域&#xff0c;我们常常关注传感器精度、算法鲁棒性、材料生物相容性这些显性指标。然而&#xff0c;有一个看似不起眼、却如同设备“心跳”般至关重要的基础元件——晶体振荡器&#xff0c;也…...

别再乱设JVM堆大小了!Elasticsearch 8.x 内存配置保姆级避坑指南

Elasticsearch 8.x 内存配置实战&#xff1a;从GC崩溃到性能巅峰的避坑手册 凌晨三点&#xff0c;服务器告警又一次响起。屏幕上的GC日志像瀑布一样滚动&#xff0c;节点频繁脱离集群&#xff0c;查询延迟突破天际——这可能是每个Elasticsearch运维人员都经历过的噩梦时刻。而…...