github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zpprof/systeminfo.go (about)

     1  /*
     2   * @Author: seekwe
     3   * @Date:   2019-05-09 16:09:12
     4   * @Last Modified by:   seekwe
     5   * @Last Modified time: 2019-05-28 15:22:30
     6   */
     7  
     8  package zpprof
     9  
    10  import (
    11  	"fmt"
    12  	"os"
    13  	"runtime"
    14  	"strconv"
    15  	"time"
    16  
    17  	"github.com/sohaha/zlsgo/zfile"
    18  )
    19  
    20  // SystemInfo SystemInfo
    21  type SystemInfo struct {
    22  	ServerName   string
    23  	Runtime      string // 运行时间
    24  	GoroutineNum string // goroutine数量
    25  	CPUNum       string // cpu核数
    26  	UsedMem      string // 当前内存使用量
    27  	TotalMem     string // 总分配的内存
    28  	SysMem       string // 系统内存占用量
    29  	Lookups      string // 指针查找次数
    30  	Mallocs      string // 内存分配次数
    31  	Frees        string // 内存释放次数
    32  	LastGCTime   string // 距离上次GC时间
    33  	NextGC       string // 下次GC内存回收量
    34  	PauseTotalNs string // GC暂停时间总量
    35  	PauseNs      string // 上次GC暂停时间
    36  	HeapInuse    string // 正在使用的堆内存
    37  }
    38  
    39  func NewSystemInfo(startTime time.Time) *SystemInfo {
    40  	var afterLastGC string
    41  	mstat := &runtime.MemStats{}
    42  	runtime.ReadMemStats(mstat)
    43  	costTime := int(time.Since(startTime).Seconds())
    44  	if mstat.LastGC != 0 {
    45  		afterLastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(mstat.LastGC))/1000/1000/1000)
    46  	} else {
    47  		afterLastGC = "0"
    48  	}
    49  
    50  	serverName, _ := os.Hostname()
    51  
    52  	return &SystemInfo{
    53  		ServerName:   serverName,
    54  		Runtime:      fmt.Sprintf("%d天%d小时%d分%d秒", costTime/(3600*24), costTime%(3600*24)/3600, costTime%3600/60, costTime%(60)),
    55  		GoroutineNum: strconv.Itoa(runtime.NumGoroutine()),
    56  		CPUNum:       strconv.Itoa(runtime.NumCPU()),
    57  		HeapInuse:    zfile.SizeFormat(uint64(mstat.HeapInuse)),
    58  		UsedMem:      zfile.SizeFormat(uint64(mstat.Alloc)),
    59  		TotalMem:     zfile.SizeFormat(uint64(mstat.TotalAlloc)),
    60  		SysMem:       zfile.SizeFormat(uint64(mstat.Sys)),
    61  		Lookups:      strconv.FormatUint(mstat.Lookups, 10),
    62  		Mallocs:      strconv.FormatUint(mstat.Mallocs, 10),
    63  		Frees:        strconv.FormatUint(mstat.Frees, 10),
    64  		LastGCTime:   afterLastGC,
    65  		NextGC:       zfile.SizeFormat(uint64(mstat.NextGC)),
    66  		PauseTotalNs: fmt.Sprintf("%.3fs", float64(mstat.PauseTotalNs)/1000/1000/1000),
    67  		PauseNs:      fmt.Sprintf("%.3fs", float64(mstat.PauseNs[(mstat.NumGC+255)%256])/1000/1000/1000),
    68  	}
    69  }