【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(…...
React Native 导航系统实战(React Navigation)
导航系统实战(React Navigation) React Navigation 是 React Native 应用中最常用的导航库之一,它提供了多种导航模式,如堆栈导航(Stack Navigator)、标签导航(Tab Navigator)和抽屉…...
rnn判断string中第一次出现a的下标
# coding:utf8 import torch import torch.nn as nn import numpy as np import random import json""" 基于pytorch的网络编写 实现一个RNN网络完成多分类任务 判断字符 a 第一次出现在字符串中的位置 """class TorchModel(nn.Module):def __in…...

论文笔记——相干体技术在裂缝预测中的应用研究
目录 相关地震知识补充地震数据的认识地震几何属性 相干体算法定义基本原理第一代相干体技术:基于互相关的相干体技术(Correlation)第二代相干体技术:基于相似的相干体技术(Semblance)基于多道相似的相干体…...
Python+ZeroMQ实战:智能车辆状态监控与模拟模式自动切换
目录 关键点 技术实现1 技术实现2 摘要: 本文将介绍如何利用Python和ZeroMQ消息队列构建一个智能车辆状态监控系统。系统能够根据时间策略自动切换驾驶模式(自动驾驶、人工驾驶、远程驾驶、主动安全),并通过实时消息推送更新车…...

打手机检测算法AI智能分析网关V4守护公共/工业/医疗等多场景安全应用
一、方案背景 在现代生产与生活场景中,如工厂高危作业区、医院手术室、公共场景等,人员违规打手机的行为潜藏着巨大风险。传统依靠人工巡查的监管方式,存在效率低、覆盖面不足、判断主观性强等问题,难以满足对人员打手机行为精…...

逻辑回归暴力训练预测金融欺诈
简述 「使用逻辑回归暴力预测金融欺诈,并不断增加特征维度持续测试」的做法,体现了一种逐步建模与迭代验证的实验思路,在金融欺诈检测中非常有价值,本文作为一篇回顾性记录了早年间公司给某行做反欺诈预测用到的技术和思路。百度…...

快速排序算法改进:随机快排-荷兰国旗划分详解
随机快速排序-荷兰国旗划分算法详解 一、基础知识回顾1.1 快速排序简介1.2 荷兰国旗问题 二、随机快排 - 荷兰国旗划分原理2.1 随机化枢轴选择2.2 荷兰国旗划分过程2.3 结合随机快排与荷兰国旗划分 三、代码实现3.1 Python实现3.2 Java实现3.3 C实现 四、性能分析4.1 时间复杂度…...

海云安高敏捷信创白盒SCAP入选《中国网络安全细分领域产品名录》
近日,嘶吼安全产业研究院发布《中国网络安全细分领域产品名录》,海云安高敏捷信创白盒(SCAP)成功入选软件供应链安全领域产品名录。 在数字化转型加速的今天,网络安全已成为企业生存与发展的核心基石,为了解…...

Java数组Arrays操作全攻略
Arrays类的概述 Java中的Arrays类位于java.util包中,提供了一系列静态方法用于操作数组(如排序、搜索、填充、比较等)。这些方法适用于基本类型数组和对象数组。 常用成员方法及代码示例 排序(sort) 对数组进行升序…...

2025-05-08-deepseek本地化部署
title: 2025-05-08-deepseek 本地化部署 tags: 深度学习 程序开发 2025-05-08-deepseek 本地化部署 参考博客 本地部署 DeepSeek:小白也能轻松搞定! 如何给本地部署的 DeepSeek 投喂数据,让他更懂你 [实验目的]:理解系统架构与原…...