测试代码如下:

#include <sys/prctl.h>
#include <pthread.h>

void *thread_routine(void *arg)
{
	prctl(PR_SET_NAME, "child_thread");
	int i = 0;
	while(1)
	{
		i++;
		i = i * 12345;
	}
	return (void *)0;
}

int main( void )
{
	pthread_t handle;
	pthread_create(&handle, NULL, thread_routine, NULL);
	pthread_join(handle, NULL);
	return 0;
}

编译成可执行文件  test.

然后,执行 test.

下面是分析这个进程里面的线程的CPU占用率.

方法1:

$ ps -C test -L -o pid,tid,psr,pcpu,comm
  PID   TID PSR %CPU COMMAND
22849 22849   3  0.0 test
22849 22850   1 99.9 child_thread
方法2:

以 top -H 执行,然后,按 f键, 按空格键 选中

P       = Last Used Cpu (SMP)

,按Esc后者 q退出,输出结果如下:

Threads: 742 total,   3 running, 738 sleeping,   0 stopped,   1 zombie
%Cpu(s): 40.6 us,  2.5 sy,  0.1 ni, 56.5 id,  0.2 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  4086928 total,   670704 free,  1989828 used,  1426396 buff/cache
KiB Swap:  4140028 total,  3609488 free,   530540 used.  1507048 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                      P 
22850 charles   20   0   10512    592    532 R 99.9  0.0  22:01.90 child_thread                 3 
28277 charles   20   0 1601204 457328 138820 R 36.8 11.2 214:36.88 Compositor                   1 
 1191 root      20   0  347380 106852  67784 S 11.1  2.6 955:34.67 Xorg                         0 
 2069 charles   20   0  422700 120328  37048 S  9.4  2.9 595:07.34 compiz                       0

或者:

$ pidof test
22849
$ top -H -p 22849
KiB Mem :  4086928 total,   335404 free,  2245788 used,  1505736 buff/cache
KiB Swap:  4140028 total,  3613268 free,   526760 used.  1263944 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND      
22850 charles   20   0   10512    592    532 R 99.9  0.0 118:54.15 child_thread 
22849 charles   20   0   10512    592    532 S  0.0  0.0   0:00.00 test 


Logo

更多推荐