ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 语法 ``` func KeepAlive(x interface{}) func LockOSThread() // 协程转为线程 func UnlockOSThread() func NumCPU() int func NumCgoCall() int64 // 返回当前进程执行的cgo调用次数 func NumGoroutine() int // 返回当前存在的Go程数 func Version() string func GC() // GC执行一次垃圾回收 func GOMAXPROCS(n int) int // 同时执行的最大CPU数 func GOROOT() func ReadMemStats(m *MemStats) func SetBlockProfileRate(rate int) // 阻塞profile记录go程阻塞事件的采样频率 func SetCPUProfileRate(hz int) // CPU profile记录的速率为平均每秒hz次 func SetMutexProfileFraction(rate int) int // 互斥配置文件中报告的互斥争用事件的比例 func StartTrace() error func StopTrace() ``` ## runtime.MemStats ``` type MemStats struct { // 一般统计 Alloc uint64 // 已申请且仍在使用的字节数 TotalAlloc uint64 // 已申请的总字节数(已释放的部分也算在内) Sys uint64 // 从系统中获取的字节数(下面XxxSys之和) Lookups uint64 // 指针查找的次数 Mallocs uint64 // 申请内存的次数 Frees uint64 // 释放内存的次数 // 主分配堆统计 HeapAlloc uint64 // 已申请且仍在使用的字节数 HeapSys uint64 // 从系统中获取的字节数 HeapIdle uint64 // 闲置span中的字节数 HeapInuse uint64 // 非闲置span中的字节数 HeapReleased uint64 // 释放到系统的字节数 HeapObjects uint64 // 已分配对象的总个数 // L低层次、大小固定的结构体分配器统计,Inuse为正在使用的字节数,Sys为从系统获取的字节数 StackInuse uint64 // 引导程序的堆栈 StackSys uint64 MSpanInuse uint64 // mspan结构体 MSpanSys uint64 MCacheInuse uint64 // mcache结构体 MCacheSys uint64 BuckHashSys uint64 // profile桶散列表 GCSys uint64 // GC元数据 OtherSys uint64 // 其他系统申请 // 垃圾收集器统计 NextGC uint64 // 会在HeapAlloc字段到达该值(字节数)时运行下次GC LastGC uint64 // 上次运行的绝对时间(纳秒) PauseTotalNs uint64 PauseNs [256]uint64 // 近期GC暂停时间的循环缓冲,最近一次在[(NumGC+255)%256] NumGC uint32 EnableGC bool DebugGC bool // 每次申请的字节数的统计,61是C代码中的尺寸分级数 BySize [61]struct { Size uint32 Mallocs uint64 Frees uint64 } } ``` ## 实例 ### ReadMemStats 获取 MemStats ``` var mem runtime.MemStats runtime.ReadMemStats(&mem) fmt.Printf("%+v\n", mem) ``` ### stack 异常打印堆栈信息 ``` defer func() { if r := recover(); r != nil { err := r.(error) log.Errorf("recover:%+v\tstackinfo:%v\n\n", err, utils.GetStackInfo()) } }() // 与 debug.Stack 相似 func GetStackInfo() string { buf := make([]byte, 4096) n := runtime.Stack(buf, false) return fmt.Sprintf("%s", buf[:n]) } ```