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:
- Include time.h header in your C program. i.e., write #include<time.h> statement before main() function.
- 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)
- Use t1=time(NULL); before the start of the algorithm/ methodology that you want to test.
- After writing algorithm/ methodology, use t2=time(NULL);
- 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