嵌入式软件开发杂谈(5):如何查看线程的CPU使用率

在正常的开发中,有时候我们需要知道当前进程的每个线程的CPU使用情况,方便对每个线程进行分析,此时就需要在top指令中显示线程的使用情况。

在使用中要使用prctl为线程重命名,不然在top中显示的就是主进程的名字,就无法确认是那个线程了。

使用指令:

#top -Hp PID
PID为进程的PID,使用后可以只看此进程的CPU使用情况。

如下:
在这里插入图片描述

或者使用指令:

#top -H

#top

然后再输入H

即可看到所有进程的线程CPU使用情况。

在这里插入图片描述

下面代码为上下截图的示例代码:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/prctl.h>

void* thread11(void* arg)
{	
	printf("----->thread11\n");
	prctl(PR_SET_NAME, "thread11");
	
    while(1)
	{
        sleep(1);
    }
}

void* thread12(void* arg)
{
	printf("----->thread12\n");
	prctl(PR_SET_NAME, "thread12");
	
    while(1)
	{
        usleep(1);
    }
}

void* thread13(void* arg)
{
	printf("----->thread13\n");
	prctl(PR_SET_NAME, "thread13");
	
    while(1)
	{
        usleep(100);
    }
}

int main()
{ 
	pthread_t thread[3];
	int s32Ret = 0;
	
	s32Ret = pthread_create(&thread[0], NULL, thread11, NULL);		
	printf("pthread_create, ret:%d\n", s32Ret);
	sleep(1);
	
	s32Ret = pthread_create(&thread[1], NULL, thread12, NULL);			
	printf("pthread_create, ret:%d\n", s32Ret);
	sleep(1);
	
	s32Ret = pthread_create(&thread[0], NULL, thread13, NULL);		
	printf("pthread_create, ret:%d\n", s32Ret);
	sleep(1);

	while(1)
	{
		sleep(1);
	}
	
	return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值