C Programming/C Reference/time.h/difftime

From Wikibooks, open books for an open world
Jump to: navigation, search

The C library provides us with difftime function which returns the time elapsed between two calendar dates. This function is defined in the header file time.h. It returns the difference (t2 - t1), where t1 is initial time and t2 is end time in seconds as a double-precision floating point number. This function is significant because there are no general arithmetic operations defined on type time_t.

The function difftime is declared in the header file "time.h".

Syntax: double difftime(time_t time2, time_t time1);

prolog: difftime subtracts time1 from time2 to calculate the time elapsed between time1 and time2. The value is calculated in seconds elapsed. The arguments are normally obtained by two calls to the time function.

Return Value: Returns the difference between time1 and time2 in seconds.

Example:

main()
{
        int sec;
        time_t start_time, finish_time;
        time(&start_time); //in time.h header file
        for ( sec = 1; sec <= 6; sec++)
        {
                printf("%d\r", sec);
                sleep(1);
        }
        time(&finish_time);
        printf("\nDifference is  %.2f seconds",difftime(finish_time, start_time));
}

Output:


6

Difference is 6.00 seconds