CPU使用率如何计算,可以参考busybox的实现
其原理是每隔5s读一次/proc/stat,两次的值相减作为CPU占用率。
/proc/stat的含义详见附件。
int top_main(int argc UNUSED_PARAM, char **argv)
cpu_jif = &cur_jif;
cpu_prev_jif = &prev_jif;
while (scan_mask != EXIT_MASK)
interval = 5; /* default update interval is 5 seconds */
sleep_for_duration(interval);
do_stats();
=>static void do_stats(void)
get_jiffy_counts();
=>static void get_jiffy_counts(void)
FILE* fp = xfopen_for_read("stat");//访问/proc/stat
read_cpu_jiffy(fp, &cpu_jif[num_cpus])
=>static NOINLINE int read_cpu_jiffy(FILE *fp, jiffy_counts_t *p_jif)
#if !ENABLE_FEATURE_TOP_SMP_CPU
static const char fmt[] ALIGN1 = "cpu %llu %llu %llu %llu %llu %llu %llu %llu";
#else
static const char fmt[] ALIGN1 = "cp%*s %llu %llu %llu %llu %llu %llu %llu %llu";
#endif
fgets(line_buf, LINE_BUF_SIZE, fp)
ret = sscanf(line_buf, fmt,
&p_jif->usr, &p_jif->nic, &p_jif->sys, &p_jif->idle,
&p_jif->iowait, &p_jif->irq, &p_jif->softirq,
&p_jif->steal);
if (ret >= 4) {
p_jif->total = p_jif->usr + p_jif->nic + p_jif->sys + p_jif->idle
+ p_jif->iowait + p_jif->irq + p_jif->softirq + p_jif->steal;
/* procps 2.x does not count iowait as busy time */
p_jif->busy = p_jif->total - p_jif->idle - p_jif->iowait;
}
display_process_list(G.lines, col);
=>static NOINLINE void display_process_list(int lines_rem, int scr_width)
unsigned long total_memory = display_header(scr_width, &lines_rem);
=>static unsigned long display_header(int scr_width, int *lines_rem_p)
display_cpus(scr_width, scrbuf, lines_rem_p);
理解Linux CPU负载和 CPU使用率
https://www.cnblogs.com/muahao/p/6492665.html
Linux CPU使用率含义及原理
https://www.cnblogs.com/aresxin/p/9152127.html
Linux CPU占用率原理与 精确度分析
https://blog.csdn.net/lmjssjj/article/details/72401474
linux cpu占用100%排查
https://blog.csdn.net/qinshi501/article/details/77442770
linux环境下cpu利用率的计算
https://blog.csdn.net/ustclu/article/details/1721673
Linux平台Cpu使用率的计算
http://www.blogjava.net/fjzag/articles/317773.html
/proc/stat 详解
https://blog.csdn.net/new_abc/article/details/12942525
【Linux】/proc/stat详解 完整验证版
https://blog.csdn.net/zd199218/article/details/80698192?utm_source=blogxgwz8
shell脚本--截取系统一分钟的平均负载,只取整数部分
https://my.oschina.net/AnnaWu/blog/1539880