Profiling Your C Program

Hello All,

When you are middle of writing an interesting function, suddenly you want to know the time taken by your own program/function call, you will be freaked out, when the dead line is in an hour.  Relax yourself. We will help you out.

Mostly we do profiling for "for/while" loops. Because these loops are used for some memory manipulation such as string comparison, etc., Therefore, we have to find out if the loop is needed or how many seconds it takes for all n entries, etc., to optimize the code.

Why profiling is needed ? 

For better optimization

Here is a code to profile your program.

#include<stdio.h>
#include<time.h>   // localtime, strftime
#include <sys/time.h> // timeval structure

void display_time_in_seconds(struct timeval *start, struct timeval *end, char *time_for)
{
    if (!start || !end || !time_for) {
        printf("display_time_in_seconds NULL value");
        return;
    }
    double disp_time = 0;
    disp_time = (end->tv_sec - start->tv_sec) +
                 ((end->tv_usec - start->tv_usec)/1000000.0);
    printf("\n\n\t\t Elapsed %s time in second = %f  second= %d Microsecond = %d \n",
           time_for, disp_time, (int)(end->tv_sec - start->tv_sec), (int)(end->tv_usec - start->tv_usec));
}

main()
{
    struct timeval time_start = {0};
    struct timeval time_end = {0};

    gettimeofday(&time_start, NULL);
    sleep(10);              // Replace this with your program
    gettimeofday(&time_end, NULL);
    display_time_in_seconds(&time_start, &time_end, "sleep");
}

Output  

  $] cc -o pro profiling.c
  $] ./pro 
  Elapsed sleep time in second = 10.000076  second= 10 Microsecond = 76


Note :  Output will be displayed after 10 seconds 

Comments