问题描述

我编写了一个 golang 程序,它在运行时使用了 1.2GB 的内存.

I wrote a golang program, that uses 1.2GB of memory at runtime.

go tool pprof http://10.10.58.118:8601/debug/pprof/heap
go tool pprof http://10.10.58.118:8601/debug/pprof/heap
  • 剩余的内存使用情况如何?
  • 有没有更好的工具来解释 golang 运行时内存?
gcvis

.. 和这个堆形式的配置文件:

.. and this heap form profile:

推荐答案

堆配置文件显示活动内存,运行时认为正在被 go 程序使用的内存(即:尚未被垃圾收集器收集).当 GC 确实收集内存时,配置文件会缩小,但没有内存返回给系统.您未来的分配将尝试使用先前收集的对象池中的内存,然后再向系统请求更多.

The heap profile shows active memory, memory the runtime believes is in use by the go program (ie: hasn't been collected by the garbage collector). When the GC does collect memory the profile shrinks, but no memory is returned to the system. Your future allocations will try to use memory from the pool of previously collected objects before asking the system for more.

从外部看,这意味着您的程序的内存使用量要么增加,要么保持水平.外部系统显示为您程序的驻留大小"的是分配给您的程序的 RAM 字节数,无论它是保存使用中的 go 值还是收集的值.

From the outside, this means that your program's memory use will either be increasing, or staying level. What the outside system presents as the "Resident Size" of your program is the number of bytes of RAM is assigned to your program whether it's holding in-use go values or collected ones.

这两个数字经常相差很大的原因是:

The reason why these two numbers are often quite different are because:

  1. GC 收集内存对程序的外观没有影响
  2. 内存碎片
  3. GC 仅在使用的内存是上次 GC 后使用的内存翻倍时才会运行(默认情况下,请参阅:http://golang.org/pkg/runtime/#pkg-overview)

如果您想准确了解 Go 如何查看内存,您可以使用 runtime.ReadMemStats 调用:http://golang.org/pkg/runtime/#ReadMemStats

If you want an accurate breakdown of how Go sees the memory you can use the runtime.ReadMemStats call: http://golang.org/pkg/runtime/#ReadMemStats

http://10.10.58.118:8601/debug/pprof/
http://10.10.58.118:8601/debug/pprof/

runtime.MemStats 文档(http://golang.org/pkg/runtime/#MemStats)有所有字段的解释,但这次讨论中有趣的是:

The runtime.MemStats documentation (http://golang.org/pkg/runtime/#MemStats) has the explanation of all the fields, but the interesting ones for this discussion are:

  • HeapAlloc:本质上是分析器给你的(活动堆内存)
  • Alloc:类似于 HeapAlloc,但适用于所有 go 托管内存
  • Sys:从操作系统请求的内存总量(地址空间)

Sys 和 OS 报告的内容之间仍然会存在差异,因为 Go 对系统的要求和 OS 提供的内容并不总是相同的.此外,go 不跟踪 CGO/syscall(例如:malloc/mmap)内存.

There will still be discrepancies between Sys, and what the OS reports because what Go asks of the system, and what the OS gives it are not always the same. Also CGO / syscall (eg: malloc / mmap) memory is not tracked by go.

这篇关于如何分析golang内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!