C/C++:系统IDLE、进程CPU占用率、CPU核心数以及进程中的线程数
TOP命令可以显示当前进程的CPU占用率、CPU核心数以及系统忙闲程度(idle)。
他们之间有什么关系呢?
实验主机配置:物理CPU*4,逻辑CPU*8。
[root@eb50 ~]# grep 'physical id' /proc/cpuinfo | sort -u
physical id : 0
physical id : 1
physical id : 2
physical id : 3
[root@eb50 ~]# grep 'processor' /proc/cpuinfo
processor : 0
processor : 1
processor : 2
processor : 3
processor : 4
processor : 5
processor : 6
processor : 7
代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
void *threadRun(void *arg)
{
fprintf(stdout, "thread=%lu\n", pthread_self());
while (1)
{
// do nothing
}
}
int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s $THREAD_NUM\n", argv[0]);
exit(1);
}
fprintf(stdout, "THREAD_NUM=%d\n", atoi(argv[1]));
int threadNum = atoi(argv[1]);
while (threadNum--)
{
pthread_t tid;
if (pthread_create(&tid, NULL, threadRun, NULL) != 0)
{
fprintf(stderr, "create thread error(%d)=%s\n", errno, strerror(errno));
exit(1);
}
}
while (1)
{
sleep(1);
}
return 0;
}
编译:
[root@eb50 20180611]# gcc -o main main.c -lpthread
[root@eb50 20180611]# ll
total 16
-rwxr-xr-x 1 root root 8340 Jun 11 22:49 main
-rw-r--r-- 1 root root 684 Jun 11 22:36 main.c
使用TOP命令查看进程占用资源情况:
top -u root
Case 1:启动1个工作线程
进程CPU占用率约为100%(99.1%),idle=87.4,实际占比:(100-87.4)/100=1/8。
Case 2:启动2个工作线程
进程CPU占用率约为200%(198.0%),idle=74.9,实际占比:(100-74.9)/100=2/8。
Case 3:启动4个工作线程
进程CPU占用率约为400%(396.2%),idle=50.0,实际占比:(100-50.0)/100=4/8。
Case 4:启动8个工作线程
进程CPU占用率约为800%(792.0%),idle=0.0,实际占比:(100-0.0)/100=8/8。
Case 5:启动10个工作线程
进程CPU占用率约为800%(791.9%),idle=0.0,实际占比:(100-0.0)/100=8/8。