一文秒懂CPU使用率( 二 )

< 2) { printf("Usage: %s pidn", argv[0]); return 0; } pid = atoi(argv[1]); if (!processExists(pid)) { printf("Process %d doesn't exist.n", pid); return 1; } if (signal(SIGALRM, tick) == SIG_ERR) { exit(0); }struct itimerval tick; memset(&tick, 0, sizeof tick); tick.it_value.tv_sec = period; tick.it_value.tv_usec = 0; tick.it_interval.tv_sec = period; tick.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &tick, NULL); while (1) { pause(); }return 0;}代码很简单,每隔两秒采一次样,计算这两秒内指定进程的CPU使用率 。
为了测试,先将前文的cputest运行起来,该程序会占满8个logic core 。
./cputest &,然后top看下CPU使用率,大约占用了800%的CPU 。
867 root 20 0 84312 616 416 S 800.0 0.0 17:44.60 cputest接着用我们的自己的写的程序看下,pid是867,
./cpumon 867
pid 867 cpu usage:786.0%pid 867 cpu usage:785.5%pid 867 cpu usage:787.5%pid 867 cpu usage:759.5%pid 867 cpu usage:781.5%pid 867 cpu usage:791.5%pid 867 cpu usage:743.5%pid 867 cpu usage:782.0%pid 867 cpu usage:777.5%pid 867 cpu usage:785.0%pid 867 cpu usage:790.5%pid 867 cpu usage:786.0%^C可以看到每隔两秒都会计算一次,使用率略低于800%,也可以理解,因为现在cpumon也会占用一定的CPU时间 。
参考资料:https://www.howtogeek.com/194756/cpu-basics-multiple-cpus-cores-and-hyper-threading-explained/
原文:https://www.cnblogs.com/gatsby123/p/11127158.html

【一文秒懂CPU使用率】


推荐阅读