Go 运行时有很多与堆和栈相关的不同变量,一些栈号是堆号的一部分,导致混淆(对我来说)。例如,in this link .它说
// Stack numbers are part of the heap numbers, separate those out for user consumption
stats.StackSys = stats.StackInuse
stats.HeapInuse -= stats.StackInuse
stats.HeapSys -= stats.StackInuse
在runtime docs (下面摘录),它给出了 7 个不同的堆相关字段(即 memstat 结构的字段),但没有明确说明哪些包含堆栈,同样,堆中包含哪些堆栈字段,以及它与总分配的关系。
这是个问题,因为我想比较堆和堆栈,但我不想选择包含堆栈的堆变量(显然)。
问题 1).总分配字段是否包括堆、堆栈或两者? 2)哪些堆字段不包括数字堆栈? 3) 哪些堆字段包括堆栈的数字? 4) 哪些堆栈字段不包括堆的数字?
Alloc uint64 // bytes allocated and still in use
TotalAlloc uint64 // bytes allocated (even if freed)
Sys uint64 // bytes obtained from system (sum of XxxSys below)
Lookups uint64 // number of pointer lookups
Mallocs uint64 // number of mallocs
Frees uint64 // number of frees
// Main allocation heap statistics.
HeapAlloc uint64 // bytes allocated and still in use
HeapSys uint64 // bytes obtained from system
HeapIdle uint64 // bytes in idle spans
HeapInuse uint64 // bytes in non-idle span
HeapReleased uint64 // bytes released to the OS
HeapObjects uint64 // total number of allocated objects
// Low-level fixed-size structure allocator statistics.
// Inuse is bytes used now.
// Sys is bytes obtained from system.
StackInuse uint64 // bytes used by stack allocator
StackSys uint64
最佳答案
这些问题有点难以回答,因为 goroutine 栈是从堆中分配的。 Go 没有 C 中存在的堆栈和堆之间的明确分离。
总分配字段是否包括堆、堆栈或两者?
MemStats 结构的 TotalAlloc 字段包括 Go 运行时从操作系统为 Go 堆请求的所有内存。它不包括为 goroutine 堆栈分配的内存。起初我认为是的,但我错了。对困惑感到抱歉。我希望这个答案更准确。
(准确地说,我应该提到,在使用 cgo 的程序中,每个线程(不是 goroutine——通常 goroutine 比线程多)将有一个由操作系统分配的堆栈;该堆栈不是由 Go 分配的运行时,不计入 TotalAlloc。它仅由 cgo 调用使用。)
哪些堆字段不包括数字堆栈? 哪些堆字段包含堆栈的数字?
这些字段包括 goroutine 堆栈的数字:HeapIdle、HeapReleased。
这些字段不包括 goroutine 堆栈的数字:HeapAlloc、HeapInUse、HeapObjects。
HeapSys 字段不包括当前事件的 goroutine 堆栈使用的内存,但包括曾经使用但随后被释放的 goroutine 堆栈的内存。
哪些堆栈字段不包含堆的数字?
我不知道如何以有意义的方式回答这个问题。堆栈字段报告专门关于 goroutine 堆栈的信息。
关于go - memstats struct 中的哪些字段只引用堆,只引用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28244595/