
获取 go 语言 gc 消耗时间
在 go 语言中,使用 runtime 包可以获取与 gc 相关的各种信息,包括消耗时间。
获取 gc 消耗时间
要获取 gc 的消耗时间,可以使用 runtime.readmemstats 函数。该函数返回一个 runtime.memstats 结构,其中包含各种 gc 相关信息,包括:
- pausetotalns: gc 暂停时间总量(以纳秒为单位)
- pausens: 上次 gc 暂停时间(以纳秒为单位)
示例代码
import "runtime"
func main() {
var stats runtime.memstats
runtime.readmemstats(&stats)
// 获取 gc 暂停时间总量(以纳秒为单位)
totalpausens := stats.pausetotalns
// 获取上次 gc 暂停时间(以纳秒为单位)
lastpausens := stats.pausens
}获取 gc 次数
除了 gc 消耗时间,还可以获取 gc 的执行次数。可以使用 runtime.numgc 获取这个值。
示例代码
import "runtime"
func main() {
// 获取 GC 执行次数
numGC := runtime.NumGC()
}其他相关信息
runtime.memstats 结构还包含其他与 gc 相关的有价值的信息,例如:
- numgoroutine: 当前活动的 goroutine 数量
- memallocated: 当前已分配的内存量
- memtotal: 所有已分配的内存量
- memsys: 系统已使用的内存量
这些信息可以帮助深入了解 go 程序的内存管理情况。










