get system cpu frequency in go

To get the system CPU frequency in Go, we can use the cpu package from the standard library. This package provides functions to query various CPU-related system information, including the current CPU frequency.

Here's an example code snippet that shows how to get the CPU frequency in Hz:

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    freq := runtime.NumCPU() * runtime.GetCPUFreq()
    fmt.Printf("CPU frequency: %v Hz\n", freq)
}
165 chars
12 lines

In this code, we first import the runtime package, which provides access to various runtime-related system information, including the number of CPUs and the CPU frequency.

To get the CPU frequency, we first call the runtime.NumCPU() function to get the number of logical CPUs on the current system. We then multiply this value with the CPU frequency returned by the runtime.GetCPUFreq() function, which gives us the current system-wide CPU frequency in Hz.

Finally, we print the CPU frequency using fmt.Printf(), with the %v verb to format the frequency value as a string. Note that the actual frequency value will depend on the specific system hardware and configuration.

related categories

gistlibby LogSnag