Я спросил ChatGPT, как это сделать, и он дал мне это:
Код: Выделить всё
func getCpuUsage() float32 {
// Read CPU times from /proc/self/stat
readCPUStat := func() (float64, error) {
data, err := ioutil.ReadFile("/proc/self/stat")
if err != nil {
return 0, err
}
// Parse the fields from /proc/self/stat
fields := strings.Fields(string(data))
// Fields[13] (utime) and Fields[14] (stime) are process CPU times in clock ticks
utime, err := strconv.ParseFloat(fields[13], 64)
if err != nil {
return 0, err
}
stime, err := strconv.ParseFloat(fields[14], 64)
if err != nil {
return 0, err
}
// Total CPU time used by the process
return utime + stime, nil
}
// Get initial CPU time and wall clock time
startCPU, _ := readCPUStat()
startTime := time.Now()
// Wait for an interval
interval := 1 * time.Second
time.Sleep(interval)
// Get CPU time and wall clock time again
endCPU, _ := readCPUStat()
endTime := time.Now()
// Calculate CPU usage percentage
cpuTimeUsed := endCPU - startCPU
totalTime := endTime.Sub(startTime).Seconds()
clockTicksPerSecond := float64(100) // Default for Linux systems
cpuUsage := (cpuTimeUsed / totalTime) / clockTicksPerSecond * 100
return float32(cpuUsage)
}
Как я могу узнать загрузку ЦП, например, если в системе есть 4 ядра, он скажет 100%, если он использует максимум из всех, я ожидаю, что проценты будут около 10%.
Я нашел решение для получения памяти с помощью библиотеки времени выполнения
Код: Выделить всё
func getMemoryUsage() int64 {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
return int64(mem.Alloc)
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... g-on-linux
Мобильная версия