Tuesday 17 February 2015

Calculate elapsed time - C Programming

Welcome to Logically Proven Blog.

This post teaches you how to measure the time taken by a function or a set of statements or a complete program.

It is very important to track the performance of our own application in certain cases where the execution time of a program plays a major role.

To calculate time taken by a process, we use clock() function which is available in a system library time.h. We can make use of available function in this library to calculate the elapsed time of a program.

For example,we want to calculate the execution time of a program, we can call the clock functions at the beginning and at the end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time.

Syntax:
#include <time.h>
 
clock_t start, end;
double elapsed_used;
 
start = clock();
... /* Do your work. */
end = clock();
elapsed_used = ((double)(end - start)) / CLOCKS_PER_SEC;
Example:
#include <stdio.h>
#include <time.h>
 
// A function that terminates when enter key is pressed
void funElapsedTime()
{
 printf("START \n");
 printf("Press enter to stop \n");
 while (1)
 {
  if (getchar())
   break;
 }
 printf("END \n");
}
 
// The main program calls function and calculates the elapsed time
int main()
{
 clock_t start,end;
 start = clock();
 funElapsedTime();
 end = clock();
 //calculate elapsed time
 double elapsed_time = ((double)(end-start)) / CLOCKS_PER_SEC; // in seconds
 
 printf("funElapsedTime took %f seconds to execute \n", elapsed_time);
 return 0;
}
 
 
/*output: START
          Press enter to stop
 
          END
   funElapsedTime took 5.010000 seconds to execute */
So you can include these clock functions anywhere in the program that you want to calculate the elapsed time.

Ref: http://www.gnu.org/software/libc/manual/html_node/CPU-Time.html

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

0 comments:

Post a Comment

 
biz.