Support mutli CPU and multi GPU systems

This commit is contained in:
Sebastiaan de Schaetzen 2025-03-14 13:53:08 +01:00
parent c06d5dcdd4
commit ff7b0a3a70

29
main.go
View File

@ -47,8 +47,8 @@ func main() {
defer ticker.Stop()
log.Printf("Starting idle monitoring. System will suspend when:\n")
log.Printf("- CPU usage < %.1f%%\n", cpuThreshold)
log.Printf("- GPU usage < %.1f%%\n", gpuThreshold)
log.Printf("- Average CPU usage across all cores < %.1f%%\n", cpuThreshold)
log.Printf("- Average GPU usage across all GPUs < %.1f%%\n", gpuThreshold)
log.Printf("- Disk I/O < %.1f MB/s\n", float64(diskThreshold)/(1024*1024))
log.Printf("- Network I/O < %.1f MB/s\n", float64(networkThreshold)/(1024*1024))
log.Printf("Over the last %v\n", monitoringPeriod)
@ -80,22 +80,35 @@ func getCurrentUsage() ResourceUsage {
timestamp: time.Now(),
}
// Get CPU usage
if cpuPercent, err := cpu.Percent(0, false); err == nil && len(cpuPercent) > 0 {
usage.cpuUsage = cpuPercent[0]
// Get CPU usage across all cores
if cpuPercent, err := cpu.Percent(0, true); err == nil && len(cpuPercent) > 0 {
// Calculate average CPU usage across all cores
var totalCPU float64
for _, percent := range cpuPercent {
totalCPU += percent
}
usage.cpuUsage = totalCPU / float64(len(cpuPercent))
}
// Get GPU usage
// Get GPU usage across all GPUs
count, ret := nvml.DeviceGetCount()
if ret == nvml.SUCCESS && count > 0 {
device, ret := nvml.DeviceGetHandleByIndex(0)
var totalGPU float64
var activeGPUs int
for i := 0; i < count; i++ {
device, ret := nvml.DeviceGetHandleByIndex(i)
if ret == nvml.SUCCESS {
utilization, ret := device.GetUtilizationRates()
if ret == nvml.SUCCESS {
usage.gpuUsage = float64(utilization.Gpu)
totalGPU += float64(utilization.Gpu)
activeGPUs++
}
}
}
if activeGPUs > 0 {
usage.gpuUsage = totalGPU / float64(activeGPUs)
}
}
// Get disk I/O
if diskStats, err := disk.IOCounters(); err == nil {