w3resource

C difftime() function

C difftime() function - Compute the difference between two calendar time values

The difftime() function is used to compute the difference in seconds between two times.

Syntax:

double difftime(time_t time1, time_t time2)

Parameters:

Name Description Required /Optional
time1 Ending time. Required
time2 Beginning time. Required

Return value from difftime()

  • The ctime() function returns a pointer to the character string result.
  • If the function is unsuccessful, it returns NULL. 

Example: difftime() function

The following example shows the usage of difftime() function.

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#define SIZE 10
 
int mark[SIZE];
 
int main(void)
{
   time_t start, finish;
   int n, even_num=0, odd_num=0;
 
   time(&start);
 
   /*  This loop finds the even and odd numbers between 1 and SIZE   */
      for (n = 1; n <= SIZE; n++)
      {
	   if(n%2 == 0) 
         {
            even_num++;
            }
        else
         odd_num++;
         printf("n = %d\n",n);
         sleep(1);
      }
   time(&finish);
   printf("Program takes an average of %f seconds "
                  "to find %d even numbers and %d odd numbers.\n",
                   difftime(finish,start)/n, even_num, odd_num);
}

Output:

n = 1
n = 2
n = 3
n = 4
n = 5
n = 6
n = 7
n = 8
n = 9
n = 10
Program takes an average of 0.909091 seconds to find 5 even numbers and 5 odd numbers.

C Programming Code Editor:

Previous C Programming: C ctime()
Next C Programming: C gmtime()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/time/c-difftime.php