Time analysis of c program

The time taken by c or cpp program is an important measure for embedded system target for optimizing the code. The Linux/Unix operating system has gprof command line utility, is used to find execution time taken by different function or modules of a c or cpp program.

Let us learn how to analyze timing profile of c or cpp program by example.

  • Save below code as sample.c
int bin_search (int value, int target[], int start, int end)
     if (start > end) {
         return -1;
  int middle = (start + end) / 2;
  if( value == target[middle])
  return middle;
  int v1, v2;
  if (value < target[middle]) {
return  bin_search(value, target, start, middle-1);
 if (value > target[middle]) { 
return bin_search(value, target, middle+1, end);
int main()
 int arr [] =  {17,18, 19, 27, 46, 78, 102, 114};
  int end = sizeof(arr)/sizeof(int);
  int status = bin_search(19,arr,0,7);
 if(status == -1)
    printf("No match found \n");
    printf("match found at index %d\n",status);
 return 0;
  • compile sample.c

alen@Alen-Vostro-1550:~$ gcc -pg -osample sample.c

  • Run the program

alen@Alen-Vostro-1550:~$ ./sample

After running this program A file with the name  gmon.out   will be created.

  • Convert the gmon.out file into .txt format using “gprof” command:

alen@Alen-Vostro-1550:~$ gprof ./sample >  sample.txt

With the content of sample.txt  gprof gives you  function’s execution time in the program . This information can be used to optimize  functions those are taking more time.

  • For flat profile


  • Call Graph


Related Contents to follow