Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring a program's running time

Tags:

profiler

I need a tool to measure a program's running time, like gprof. But the resolution of gprof is not good enough (about 0.01 second). oprofile seems can do it, I will try to learn how to get the data about the time info, but I can't.

So, who can tell me the steps how to do it, or anyone knows other tool can do the same thing?

like image 954
martin Avatar asked Feb 28 '23 15:02

martin


1 Answers

Measuring runtime over a whole program's execution is seldom useful with high resolution; there's too much overhead that you generally don't want to include when you're profiling things.

It's often better to measure the execution time of some critical path only, and even then it's often a good idea to repeat the execution of that path many times, to improve timing accuracy.

Under Linux/POSIX systems, gettimeofday() is often used for such timing, it has microsecond precision:

#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;
}

The above assumes that my_interesting_function() is the function whose performance you want to measure. Of course tweak the number of repetitions depending on the actual runtime of the function.

like image 160
unwind Avatar answered Mar 07 '23 00:03

unwind