摘自C语言论坛。

写好程序,用gcc编译,带上-pg参数,然后运行以后分析gmon.out文件:


starwing@starwing-desktop:~/Work/prj$ cat test.c
#include
#include

int func(int i)
{
return i <= 2 ? 1 : func(i - 1) + func(i - 2);
}

int main(void)
{

printf("zzz: %d\n", func(20));
return 0;
}
/* cc: cmd='' */
starwing@starwing-desktop:~/Work/prj$ gcc -o test -pg test.c
starwing@starwing-desktop:~/Work/prj$ ./test
zzz: 6765
starwing@starwing-desktop:~/Work/prj$ gprof ./test ./gmon.out


另一个C语言:

/**
* file_name: time_lost.c
* description:
*
* version: 1.0
* created: 3:32 2009-7-21
* revision: none
* compiler: gcc 4.3.3
*
* author: prankmoon@gmail.com
* company:
*/

#include
#include

/* just for test */
int foo(int n)
{
int i;
int sum = 0;
for (i=0; i {
sum += n;
}

return sum;
}

/* test function */
void time_lost()
{
unsigned int start_high, start_low;
unsigned int end_high, end_low;
long long time_lost, start, end;

/* here is the core :D */
asm("rdtsc \n\t");
asm("movl %%eax, %0\n\t":"=g"(start_low));
asm("movl %%edx, %0\n\t":"=g"(start_high));
printf("start_high:\t%08X start_low:\t%08X\n", start_high, start_low);
start = start_high;
start = (start << 32) | start_low;

/* invoke the target function */
foo(100);

asm("rdtsc \n\t");
asm("movl %%eax, %0\n\t":"=g"(end_low));
asm("movl %%edx, %0\n\t":"=g"(end_high));
printf("end_high:\t%08X end_low:\t%08X\n", end_high, end_low);
end = end_high;
end = (end << 32) | end_low;

/* we did it */
printf("lost time is:\t%llX\n", end - start);

return;
}

int main(int argc, char *argv[])
{
time_lost();

return 0;
}

上一篇:
下一篇:

相关文章:

Categories: 博客记录

1 Responses so far.

  1. Jak Wings 说:

    呃,下面那个竟然是纳秒级的……服了 Orz

Leave a Reply