How to get CPU usage

前端 未结 6 1799
刺人心
刺人心 2020-12-22 23:55

My Go program needs to know the current cpu usage percentage of all system and user processes.

How can I obtain that?

6条回答
  •  囚心锁ツ
    2020-12-23 00:27

    Here is an OS independent solution using Cgo to harness the clock() function provided by C standard library:

    //#include 
    import "C"
    import "time"
    
    var startTime = time.Now()
    var startTicks = C.clock()
    
    func CpuUsagePercent() float64 {
        clockSeconds := float64(C.clock()-startTicks) / float64(C.CLOCKS_PER_SEC)
        realSeconds := time.Since(startTime).Seconds()
        return clockSeconds / realSeconds * 100
    }
    

提交回复
热议问题