Wednesday, April 8, 2020

Using time() functions in C programs to calculate time taken to execute set of statements

Following is the procedure to use time() functions in C. These functions help us to calculate total time taken (in seconds) to execute a set of statements. This is very helpful if we are testing the efficiency of any algorithm / methodology:

  1. Include time.h header in your C program. i.e., write #include<time.h> statement before main() function.
  2. Inside main(), define two variables t1 and t2 whose data type is time_t. i.e, write time_t t1, t2; t1 is used to record initial time (in seconds) and t2 is used to record elapsed time (in seconds)
  3. Use t1=time(NULL); before the start of the algorithm/ methodology that you want to test.
  4. After writing algorithm/ methodology, use t2=time(NULL); 
  5. Total time taken can now be calculated as: t2-t1. Following sample example shows the usage of time() functions in C programs:

#include<stdio.h>
#include<time.h>

main()
{
        time_t t1, t2;
        int flag=0;
        unsigned long long int i, j, n;

        printf("Enter N:\n");
        scanf("%llu", &n);
        t1=time(NULL);
        for(i=2;i<=n/2;i++)
        {
                if(n%i==0)
                {
                     flag=1;
                     break;
                }
        }
        t2=time(NULL);
        printf("Time taken (in seconds): %d\n", t2-t1);
}

Execute the above program by providing large values of N and note the time it takes (in seconds) to check whether N is prime or not.

No comments:

Post a Comment

PPT + Video on Evaluation of Mathematical Series using Loops

This video introduces the approaches to evaluate mathematical infinite series, namely: 1) Euler's Series 2) Sine Series Kindly go t...