In Go, you can use the syscall
package to access low-level system information and statistics. The syscall
package provides a set of functions and constants that wrap the underlying system calls.
Here is an example of how to use syscall
to access the CPU usage statistics:
package main
import (
"fmt"
"syscall"
"time"
)
func main() {
var rusage syscall.Rusage
for {
err := syscall.Getrusage(syscall.RUSAGE_SELF, &rusage)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print the CPU user time (in seconds)
fmt.Println("CPU User Time:", rusage.Utime.Sec)
// Print the CPU system time (in seconds)
fmt.Println("CPU System Time:", rusage.Stime.Sec)
// Sleep for 1 second before getting the next statistics
time.Sleep(1 * time.Second)
}
}
In this example, we use the Getrusage
function to get the resource usage statistics for the current process (RUSAGE_SELF
). We pass a pointer to a syscall.Rusage
struct, which will be populated with the statistics.
We can then access various fields of the syscall.Rusage
struct to obtain the desired system information. In this case, we print the CPU user time and the CPU system time.
Note that the syscall
package provides access to a wide range of system calls and statistics. You can refer to the Go documentation and the relevant platform-specific documentation to explore more options and functions provided by syscall
.