Skip to content

Commit

Permalink
Uses go's monotonic clock instead.
Browse files Browse the repository at this point in the history
  • Loading branch information
Alliballibaba2 committed Jan 16, 2025
1 parent a43d2c0 commit 7614435
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions internal/cpu/cpu_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ var cpuCount = runtime.GOMAXPROCS(0)
// if CPUs are not busy, most threads are likely waiting for I/O, so we should scale
// if CPUs are already busy we won't gain much by scaling and want to avoid the overhead of doing so
func ProbeCPUs(probeTime time.Duration, maxCPUUsage float64, abort chan struct{}) bool {
var start, end, cpuStart, cpuEnd C.struct_timespec
var cpuStart, cpuEnd C.struct_timespec

// note: clock_gettime is a POSIX function
// on Windows we'd need to use QueryPerformanceCounter instead
C.clock_gettime(C.CLOCK_MONOTONIC, &start)
start := time.Now()
C.clock_gettime(C.CLOCK_PROCESS_CPUTIME_ID, &cpuStart)

select {
Expand All @@ -29,12 +29,11 @@ func ProbeCPUs(probeTime time.Duration, maxCPUUsage float64, abort chan struct{}
case <-time.After(probeTime):
}

C.clock_gettime(C.CLOCK_MONOTONIC, &end)
C.clock_gettime(C.CLOCK_PROCESS_CPUTIME_ID, &cpuEnd)

elapsedTime := float64(end.tv_sec-start.tv_sec)*1e9 + float64(end.tv_nsec-start.tv_nsec)
elapsedTime := float64(time.Since(start).Nanoseconds())
elapsedCpuTime := float64(cpuEnd.tv_sec-cpuStart.tv_sec)*1e9 + float64(cpuEnd.tv_nsec-cpuStart.tv_nsec)
cpuUsage := elapsedCpuTime / elapsedTime / float64(cpuCount)

println("CPU usage:", int(cpuUsage*100))
return cpuUsage < maxCPUUsage
}

0 comments on commit 7614435

Please sign in to comment.