C Language Time and Date Functions

The time functions, provided by C libraries are used to interact with system time routines. And with these functions we can also output current time and date various formats on the screens.

To make use of time and date function in C program, we have to include the time.h header file from the standard C library. The time.h header file contains function and macros that provides standardised access to time and date. It also contains functions to manipulate and format the time and date output.

Some of the main functions available in time.h library is as follows :

Function Description
time() This function is used to get current system time as structure
clock() This function is used to get current system time
difftime() This function is used to get the difference between two given times
strftime() This function is used to modify the actual time format
mktime() This function interprets tm structure as calendar time
localtime() This function shares the tm structure that contains date and time informations
gmtime() This function shares the tm structure that contains date and time informations
ctime() This function is used to return string that contains date and time informations
asctime() Time structure contents are interpreted by this function as calendar time. This time is converted into string.

time function() :

The time() function is used to get current system time as structure and it returns the type time_t. The time that is returned represents the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. It’s also called UNIX EPOCH time.

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

int main() {
  time_t mytime;
  mytime = time(NULL);
  printf(ctime(&mytime));
  return 0;
}
Output :

Fri Sep 28 17:21:27 2018

clock() function :

The  clock() function returns an approximation of processor time used by the program. It returns the number of seconds of type clock_t. Example :
#include <stdio.h>
#include <time.h>

int main() {
  int i;
  clock_t CPUtime1 = clock();
  printf("CPU Start time is : %ld\n", CPUtime1);
  // dummy for loop
  for(i=0;i<50000000;i++);
  clock_t CPUtime2 = clock();
  printf("CPU End time is : %ld\n", CPUtime2);
  return 0;
} 
Output :

CPU Start time is : 1503
CPU End time is : 195402

difftime() Function :

The difftime() function is used to get the difference between two given times. It returns the number of seconds of type double. Example :
#include <stdio.h>
#include <time.h>

int main() {
  int c;
  time_t beg, end;
  beg = time(NULL);
  for(c=0;c<500000000;c++);
  end = time(NULL);
  printf("For loop used %f seconds to complete.\n", difftime(end, beg));
  return 0;
}
Output :

For loop used 2.000000 seconds to complete.

No comments:

Post a Comment