Accurate calculation of CPU usage given in percentage in Linux?

后端 未结 5 1841
挽巷
挽巷 2020-11-29 16:23

It\'s a question which has been asked many times, however there is no well supported answer I could find.

Many people suggest the use of top command, but if you run

5条回答
  •  旧巷少年郎
    2020-11-29 16:51

    According the htop source code, my assumptions looks like they are valid:

    (see static inline double LinuxProcessList_scanCPUTime(LinuxProcessList* this) function at LinuxProcessList.c)

    // Guest time is already accounted in usertime
    usertime = usertime - guest;                             # As you see here, it subtracts guest from user time
    nicetime = nicetime - guestnice;                         # and guest_nice from nice time
    // Fields existing on kernels >= 2.6
    // (and RHEL's patched kernel 2.4...)
    unsigned long long int idlealltime = idletime + ioWait;  # ioWait is added in the idleTime
    unsigned long long int systemalltime = systemtime + irq + softIrq;
    unsigned long long int virtalltime = guest + guestnice;
    unsigned long long int totaltime = usertime + nicetime + systemalltime + idlealltime + steal + virtalltime;
    

    And so, from fields listed in the first line of /proc/stat: (see section 1.8 at documentation)

         user    nice   system  idle      iowait irq   softirq  steal  guest  guest_nice
    cpu  74608   2520   24433   1117073   6176   4054  0        0      0      0
    

    Algorithmically, we can calculate the CPU usage percentage like:

    PrevIdle = previdle + previowait
    Idle = idle + iowait
    
    PrevNonIdle = prevuser + prevnice + prevsystem + previrq + prevsoftirq + prevsteal
    NonIdle = user + nice + system + irq + softirq + steal
    
    PrevTotal = PrevIdle + PrevNonIdle
    Total = Idle + NonIdle
    
    # differentiate: actual value minus the previous one
    totald = Total - PrevTotal
    idled = Idle - PrevIdle
    
    CPU_Percentage = (totald - idled)/totald
    

提交回复
热议问题