facebook like button

22 November, 2011

Getting running time of a C program

The need:
     Need is obvious.Whenever you are curious to find running time of a program or you are asked to do so, you can use this program. All you need to do is to place your program code(the code between the brackets of main() function ) in between the comments which indicate the start and end of the program.
The code:
----------------------------------------------------------
/*This program is intended to work on linux*/
#include <stdio.h> 
#include <time.h> 
void print_time_diff(struct timespec begin,struct timespec end);
int main ( void )
{
    struct timespec start, end;
    gettimeofday(&start, NULL);
    //program code begins
    //program code ends
    gettimeofday(&end, NULL);
    print_time_diff(start,end);
    return 0;
}

void print_time_diff(struct timespec begin,struct timespec end)
{
    unsigned int sec,nanosec;
    if (end.tv_nsec<begin.tv_nsec) {
        sec = end.tv_sec-begin.tv_sec-1;
        nanosec = 1000000000+end.tv_nsec-begin.tv_nsec;
    } else {
        sec = end.tv_sec-begin.tv_sec;
        nanosec = end.tv_nsec-begin.tv_nsec;
    }
    printf("your program took %d seconds and %u nanoseconds to run.\n",sec,nanosec);
} 
----------------------------------------------------------
Approach:
   The approach is simple. There is a built-in structure timespec in <time.h> header file of linux.The built-in definition of structure is:
struct timespec
  {
    __time_t tv_sec;        /* Seconds.  */
    long int tv_nsec;        /* Nanoseconds.  */
  };
The program declares 2 struct variables start and end. built-in function gettimeofday() fills the struct variable passed to it with suitable values at that particular instance. This implies that start gets the value of time when your program (code to be measured) is just about to start and end gets the value of time as soon as your program finishes.
print_time_diff() is user defined function which prints the difference of the two times passed to it as arguments.
Remarks:
1. This program should not work on windows and operating systems other than linux.
2. The program which would work on windows will be posted shortly.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply