C library - difftime() function



The C library difftime() function is used to returns the difference of two times. Both the times are specified in calendar time, which represents the time elapsed since the Epoch (00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)).

Syntax

Following is the syntax of the C library difftime() function −

double difftime(time_t time1, time_t time2)

Parameters

This function accepts the following parameters −

  • time1 − This is the time_t object for end time.

  • time2 − This is the time_t object for start time.

Return Value

This function returns the difference of two times (time1 - time2) as a double value.

Example 1

Following is the basic C library program to demonstrates the difftime() function.

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

int main () {
   time_t start_t, end_t;
   double diff_t;

   printf("Starting of the program...\n");
   time(&start_t);

   printf("Sleeping for 5 seconds...\n");
   sleep(5);

   time(&end_t);
   diff_t = difftime(end_t, start_t);

   printf("Execution time = %f\n", diff_t);
   printf("Exiting of the program...\n");

   return(0);
}

Output

The above code produces the following result −

Starting of the program...
Sleeping for 5 seconds...
Execution time = 5.000000
Exiting of the program...

Example 2

In this program, we measures the time elapsed during a sleep interval and calculates the difference between two time points(t1 and t2).

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

int main() 
{ 
   int sc; // second 
   time_t t1, t2; 

   // Current time 
   time(&t1); 
   for (sc = 1; sc <= 4; sc++) 
	sleep(1); 

   // time after sleep in loop. 
   time(&t2); 
   printf("Difference is %.2f seconds", 
   difftime(t2, t1)); 

   return 0; 
}

Output

The above code produces the following result −

Difference is 4.00 seconds

Example 3

Below the example uses nested for loop iteration to subtract the begin time from the end time using difftime(). Thus, the result is printed as the total time required for the loops to execute.

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

int main()
{
   time_t begin, end;
   long long prod;

   time(&begin);
   for(int i=0; i<10000; i++)
   {
      for(int j=0; j<100000; j++)
      {
         prod = i*j;
      }
   }
   time(&end);
   printf("Time required = %f seconds", difftime(end, begin));
   return 0;
}

Output

On execution of above code, we get the following result −

Time required = 2.000000 seconds
Advertisements