开发工具: Goland

编程语言: Golang

参考:

内存分析器

内存分析器通过显示函数和分配的堆来分析和识别内存泄漏和总体内存使用情况。 要运行内存分析,请打开 _test.go 文件,然后点击间距区域中的 Run(运行)图标并选择 Profile with Memory Profiler(使用内存分析器分析)。

这里的分析数据也以相同的三种方式表示:火焰图、调用树和方法列表。 下面的火焰图数据显示了分配的空间和对象,并以更详细的视图显示了正在使用的对象和空间:

由于小分配直接影响执行速度,可以通过减少小对象的数量来实现内存优化。

调用树显示了内存中对象的内存使用情况,方法列表显示的数据与火焰图中的相同,但显示的方式是表格,可供浏览各个方法和筛选调用:

1.通过通过在show选择,查看空间和对象

点击 allocated space 查看分配的空间

点击 allocated object 查看分配的对象

点击 in-use object 查看在用的对象

点击 in-use space 查看在用的空间

2.可以通过在上面,选择三种表示方式

Flame Graph: 火焰图

Call Tree: 调用树

Method List: 方法列表

3.里面又分

Allocated spcae(bytes) :分配的空间

Own Allocated space(bytes):自己分配的空间

示例

查看 Method List ,查看 Allocated space
Method                                      Allocated space (bytes)  Own Allocated space (bytes)
command-line-arguments.TestHJ24             13,122,978               0
command-line-arguments.Chorus               13,122,978               0
testing.tRunner                             13,122,978               0
command-line-arguments.maxIncrementalQueue  10,487,192               10,487,192
command-line-arguments.maxDecreaseQueue     8,928,338                2,635,786

maxIncrementalQueue 是自定义的一个查询递增最长队列的方法

maxDecreaseQueue 是自定义的一个查询递减最长队列的方法

如何跳转到对应方法,右击 jump to source ,可以跳转

但是这是基于两个文件进行的test,好像没有办法正常跳转 testing.tRunner可以正常 command-line-arguments.maxIncrementalQueue 无法跳转,但是直到是哪一个函数

问题:

go test 遇到的同一个包下的函数报错undefined

go test .\HJ24_test.go
# command-line-arguments [command-line-arguments.test]
.\HJ24_test.go:11:2: undefined: Chorus
FAIL    command-line-arguments [build failed]
FAIL

函数位于同层 HJ24.go 中

原因是go test会为指定的源码文件生成一个虚拟代码包——“command-line-arguments”,而HJ24_test.go引用了其他包中的数据并不属于代码包“command-line-arguments”,编译不通过,错误自然发生了。

因此,我们可以在go test的时候加上引用的包。

//执行整个测试文件
go test -v HJ24_test.go HJ24.go
//执行测试文件中的指定方法
go test -v HJ24_test.go HJ24.go -test.run TestHJ24
//若文件存在多级依赖,可以直接在包目录下执行go test,运行包下所有的测试文件
go test

参考:go test遇到的同一包下的变量报错undefined

Goland中如何处理呢?

只需要在点击 Profile with 'Memory Profiler' 运行报错页面(这是是准备通过test,查看内存占用情况),点击设置

这里 Test kind 是File,只需要在Files中将 HJ24.go 同时选中运行即可,结果为


GOROOT=D:\Program Files\Go #gosetup
GOPATH=D:\go #gosetup
"D:\Program Files\Go\bin\go.exe" test -c -o C:\Users\whoami\AppData\Local\JetBrains\GoLand2024.1\tmp\GoLand\___1TestHJ24_in_HJ24_test_go.test.exe D:\src\testfile\golang\projects\华为机试\HJ24_test.go D:\src\testfile\golang\projects\华为机试\HJ24.go #gosetup
"D:\Program Files\Go\bin\go.exe" tool test2json -t C:\Users\whoami\AppData\Local\JetBrains\GoLand2024.1\tmp\GoLand\___1TestHJ24_in_HJ24_test_go.test.exe -test.v -test.paniconexit0 -test.run ^\QTestHJ24\E$ -test.memprofile C:\Users\whoami\AppData\Local\JetBrains\GoLand2024.1\profiler\华为机试.47f036a0\Memory_profile__TestHJ24_in_HJ24_test_go_ #gosetup
=== RUN   TestHJ24
423
--- PASS: TestHJ24 (0.02s)
PASS

Process finished with the exit code 0

标签: Go

添加新评论