2021-08-14 21:19:37 +00:00
package stats
import (
"fmt"
"math"
"os"
"runtime"
"github.com/struCoder/pidusage"
)
type StatCPU struct {
// Percent of CPU Usage
Usage string
2021-08-19 15:17:58 +00:00
// NumCPU returns the number of logical CPUs usable by the current process.
//
// The set of available CPUs is checked by querying the operating system at process startup. Changes to operating system CPU allocation after process startup are not reflected.
2021-08-14 21:19:37 +00:00
Num int
2021-08-19 15:17:58 +00:00
// GOARCH is the running program's architecture target: one of 386, amd64, arm, s390x, and so on.
2021-08-14 21:19:37 +00:00
Arch string
2021-08-19 15:17:58 +00:00
// Process ID
PID int
2021-08-14 21:19:37 +00:00
}
// Get CPU stats
2021-08-15 19:17:14 +00:00
func CPU ( ) ( StatCPU , error ) {
2021-08-14 21:19:37 +00:00
pid := os . Getpid ( )
stat := StatCPU {
2021-08-19 15:17:58 +00:00
Num : runtime . NumCPU ( ) ,
Arch : runtime . GOARCH ,
PID : pid ,
2021-08-14 21:19:37 +00:00
}
2021-08-15 19:17:14 +00:00
sysInfo , err := pidusage . GetStat ( pid )
if err != nil {
stat . Usage = "error"
return stat , err
}
stat . Usage = fmt . Sprint ( math . Round ( sysInfo . CPU * 100 ) / 100 , "%" )
return stat , nil
2021-08-14 21:19:37 +00:00
}