测量程序的运行时间

mar*_*tin 4 profiler

我需要一个工具来测量程序的运行时间,比如gprof.但是gprof的分辨率还不够好(约0.01秒).oprofile似乎可以做到,我将尝试学习如何获取有关时间信息的数据,但我不能.

那么,谁能告诉我如何做到的步骤,或者任何人都知道其他工具可以做同样的事情?

unw*_*ind 6

在整个程序的执行上测量运行时很少用于高分辨率; 在分析事物时,通常不希望包含太多的开销.

通常最好只测量一些关键路径的执行时间,即使这样,重复多次执行该路径通常也是一个好主意,以提高时序精度.

在Linux/POSIX系统下,gettimeofday()经常用于这种时序,它具有微秒精度:

#include <sys/time.h>
#include <time.h>
#include <stdio.h>

int main(void)
{
  struct timeval then, now;
  int i;

  gettimeofday(&then, NULL);
  for(i = 0; i < 100000; i++)
    my_interesting_function();
  gettimeofday(&now, NULL);

  printf("Did %d executions in %.3g seconds\n", i, now.tv_sec - then.tv_sec + 1e-6 * (now.tv_usec - then.tv_usec));

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

以上假设这my_interesting_function()是您要测量其性能的函数.当然,根据函数的实际运行时间调整重复次数.