嵌入式软件开发杂谈(9):如何查找CPU使用率最高的函数---pref的使用

在前面文章《嵌入式软件开发杂谈(5):线程的CPU使用率》中简单介绍了如何查看线程的CPU使用率,那么问题来了,知道了某个进程或者线程的CPU使用率,那么如何知道是那个函数导致的CPU使用率升高呐?

最方便的方法是使用perf工具,perf是一款性能分析工具,不仅可以用来分析系统全局性性能,还可以Fenix进程线程级别的性能,甚至到函数以及汇编级别,这里不介绍perf的用法,有兴趣的可以百度下。

参考前面文章的代码,测试代码如下:

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

int test_sqrt()
{
	double value = 0;
	int i = 0;
	
	for (i = 0; i < 1000000; i++)
		value += sqrt(i*i*i*i);
	
	return 0;
}

void* thread11(void* arg)
{	
	printf("----->thread11\n");
	prctl(PR_SET_NAME, "thread11");
	
    while(1)
	{
		test_sqrt();
        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;
}

将其编译并生成可执行文件test,并执行

我们使用perf top指令,可以查看占用CPU时钟最多的函数或指令,如下
在这里插入图片描述

上面字段中的Overhead表示该Symbol事件在所有采样中的比例,可以看到进程test 中的test_sqrt 占用的采样数比例较高。

我们可以单独分析进程test这个进程的情况,使用下面指令:

#perf top -g -p 841

-g 表示开启调用关系分析 -p 指定某个进程号 841为test的进程号
在这里插入图片描述

如上,为详细的信息,我们可以使用“方向键”选择test_sqrt,然后再按下“回车键”查看调用关系
在这里插入图片描述

如上,可以看到thread11中的test_sqrt函数占用的比例较高

猜你喜欢

转载自blog.csdn.net/u011003120/article/details/122172105
今日推荐