C programming difftime time.h


In C programming the <time.h> difftime function compute the difference between two calendar times.The declaration of the function is given below.

double difftime(time_t time1, time_t time0);

Parameters:
time1 -The second calendar time.This is usually the time recorded at the end of certain operation.

time0 -The first calendar time.This is the time recorded before any process is begin.

Return type
double -Returns ‘time1-time0’.

Here calendar time means the current date according to the Gregorian calendar and time.The common way to obtain ‘time_t’ value is to call the ‘time()’ function.This function simply note the current time.A code example is given below to compute the time taken to compute the sum “1 + 2 + 3 + 4 + 5 +…+ 99899999 + 99900000”.

Code example

long double sum = 0 ;

time_t start, stop;

//compute time taken to evaluate ‘1 + 2 + 3 + 4 + 5 +…+ 99899999 + 99900000’
time(&start);

for(int i=1; i<=99900000 ; i++)
{
sum = i+sum ;
}

time(&stop);

printf(“Time taken=%lesec”, difftime(stop , start) );
printf(“\n\nFac=%Lf”, sum);

Output in VS,

Time taken=1.000000e+00sec

Fac=4990005049950000.000000

The sum may not be accurate here.


Related links

->C time time.h