diff --git a/cpu/cpu_darwin.go b/cpu/cpu_darwin.go index 3d3455ee6..ff3829249 100644 --- a/cpu/cpu_darwin.go +++ b/cpu/cpu_darwin.go @@ -93,11 +93,24 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { // Use the rated frequency of the CPU. This is a static value and does not // account for low power or Turbo Boost modes. - cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency") - if err != nil { - return ret, err + + // This works for Intel macs. + if cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency"); err == nil { + c.Mhz = float64(cpuFrequency) / 1000000.0 + } else { + // On Apple Silicon fallback to hw.tbfrequency and kern.clockrate[hz] + tbFreq, err := unix.SysctlUint64("hw.tbfrequency") + if err != nil { + return append(ret, c), err + } + + kernClockrate, err := unix.SysctlClockinfo("kern.clockrate") + if err != nil { + return append(ret, c), err + } + + c.Mhz = (float64(tbFreq) * float64(kernClockrate.Hz)) / 1000000.0 } - c.Mhz = float64(cpuFrequency) / 1000000.0 return append(ret, c), nil } diff --git a/v3/cpu/cpu_darwin.go b/v3/cpu/cpu_darwin.go index 73151b40f..b4cf2838e 100644 --- a/v3/cpu/cpu_darwin.go +++ b/v3/cpu/cpu_darwin.go @@ -93,11 +93,24 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { // Use the rated frequency of the CPU. This is a static value and does not // account for low power or Turbo Boost modes. - cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency") - if err != nil { - return ret, err + + // This works for Intel macs. + if cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency"); err == nil { + c.Mhz = float64(cpuFrequency) / 1000000.0 + } else { + // On Apple Silicon fallback to hw.tbfrequency and kern.clockrate[hz] + tbFreq, err := unix.SysctlUint64("hw.tbfrequency") + if err != nil { + return append(ret, c), err + } + + kernClockrate, err := unix.SysctlClockinfo("kern.clockrate") + if err != nil { + return append(ret, c), err + } + + c.Mhz = (float64(tbFreq) * float64(kernClockrate.Hz)) / 1000000.0 } - c.Mhz = float64(cpuFrequency) / 1000000.0 return append(ret, c), nil }