使用 gprof 监测程序性能 (1)

代码如下 5.c:

#include 
#include 
#include 

void foo(int i)
{
	printf("%d\n", i);
}

void *thread( void *arg)
{
	ProfilerRegisterThread();
	int i = 0;
	while(1)
	{
		foo(i++);
		if(i == 100000)
		{
			break;
		}
	}
	return 0;
}

int main(void)
{
//	ProfilerStart("5.prof");
	pthread_t tid;
	pthread_create(&tid, NULL, thread, NULL);
	pthread_join(tid, NULL);
//	ProfilerStop();
	return 0;
}

编译:

gcc 5.c  -lpthread -lprofiler -g -o 5 -L /home/charles/install/lib  -I /home/charles/install/include/

运行:

LD_PRELOAD=/home/charles/install/lib/libprofiler.so CPUPROFILE=5.prof ./5

会生成结果文件 5.prof.

使用 pprof 分析结果:

$ pprof  --text ./5 5.prof
Using local file ./5.
Using local file 5.prof.
Total: 26 samples
      16  61.5%  61.5%       16  61.5% 0xb7783c31
       6  23.1%  84.6%        6  23.1% 0xb7783c2f
       2   7.7%  92.3%        2   7.7% _IO_vfprintf_internal
       1   3.8%  96.2%        1   3.8% _IO_new_file_overflow
       1   3.8% 100.0%        1   3.8% _IO_new_file_write
       0   0.0% 100.0%        2   7.7% __clone
       0   0.0% 100.0%        2   7.7% __printf
       0   0.0% 100.0%        2   7.7% start_thread
       0   0.0% 100.0%        2   7.7% thread
$ pprof  --pdf ./5 5.prof > 5.pdf
Using local file ./5.
Using local file 5.prof.

如果在代码中使用了 
ProfilerStart("5.prof")
ProfilerStop();
直接执行

./5

就会自动生成结果文件 5.prof


注意点:

1. 分析线程的时候,需要在线程入口函数调用 

ProfilerRegisterThread()
2. 使用 gperf 的时候,程序必须能正常退出。

当程序无法正常退出时,可以发信号给程序,在信号处理函数里面调用

ProfilerStop();
之后, prof文件才会有数据输出。

#include 
#include 
#include 
#include 
#include 

void signal_handler(int signo)
{
	if( signo == SIGTERM)
	{
		ProfilerStop();
		exit(0);
	}
}

void foo(int i)
{
	printf("%d\n", i);
}

void *thread( void *arg)
{
	ProfilerRegisterThread();
	int i = 0;
	while(1)
	{
		foo(i++);
	}
	return 0;
}

int main(void)
{
	ProfilerStart("5.prof");
	signal(SIGTERM, &signal_handler);
	pthread_t tid;
	pthread_create(&tid, NULL, thread, NULL);
	pthread_join(tid, NULL);
	ProfilerStop();
	return 0;
}


你可能感兴趣的:(Linux)