C Programming

How to use gettimeofday function in C language?

The gettimeofday() function gets the system’s clock time. The current time is expressed in elapsed seconds and microseconds since 00:00:00, January 1, 1970 (Unix Epoch). In this article, we are going to show you how to use the gettimeofday() function in Linux. So, let’s get started.

Syntax

int gettimeofday ( struct timeval *tp ,  struct timezone *tz )

The gettimeofday() function is defined in sys/time.h header file.

Arguments

This function takes two arguments:

The 1st argument points to the timeval structure. The timeval structure is declared as below in sys/time.h header file :

struct    timeval  {
  time_t        tv_sec ;   //used for seconds
  suseconds_t       tv_usec ;   //used for microseconds
}

The struct timeval structure represents a calendar time. It has two members:

  • tv_sec : It is the number of seconds since the epoch.
  • tv_usec :It is additional microseconds after number of seconds calculation since the epoch. .

The 2nd argument points to the timezone structure. It should normally be set to NULL because struct timezone is obsolete. This argument is for backwards compatibility only.

Return values

On success, the gettimeofday() return 0, for failure the function returns -1.

Simple Get Time and Print

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

int main() {
  struct timeval current_time;
  gettimeofday(&current_time, NULL);
  printf("seconds : %ld\nmicro seconds : %ld",
    current_time.tv_sec, current_time.tv_usec);

  return 0;
}

Output:

Here, sys/time.h has been included for gettimeofday() function and timeval structure. The gettimeofday() function set the time in timeval (current_time) structure member. tv_sec is the integral number of seconds elapsed since the start of the UNIX epoch, on midnight UTC on January 1, 1970 and tv_usec is additional number of microseconds elapsed from tv_sec. If you run the program you should see the output. Each time you run the program the output will change.

NULL Argument Error

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

int main() {
 
  struct timeval current_time;
  gettimeofday(NULL, NULL);
  return 0;
}

Output:

In this example shows that first argument of the gettimeofday() function should not be NULL. Compilation warning will come if the first argument is NULL.

Formatting Current Time Example

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

int main() {
  struct timeval tv;
  time_t t;
  struct tm *info;
  char buffer[64];
 
  gettimeofday(&tv, NULL);
  t = tv.tv_sec;

  info = localtime(&t);
  printf("%s",asctime (info));
  strftime (buffer, sizeof buffer, "Today is %A, %B %d.\n", info);
  printf("%s",buffer);
  strftime (buffer, sizeof buffer, "The time is %I:%M %p.\n", info);
  printf("%s",buffer);

  return 0;
}

Output:

In this example shows how to print Date and Time in different format. It is not a very easy to represent dates from the return value of gettimeofday() function . Here, localtime() and strftime() functions are used to nicely represent the return value of gettimeofday().

 

The localtime() function takes an argument, which is a reference to a pointer of the tv_sec field of struct timeval and returns a reference to a pointer of a struct tm object.

 

The strftime() function will generate a personalized, formatted string showing the date and time from the struct tm pointer. Format specifiers are used for formatted display. For example, the format string “%d-%m-%Y %H:%M:%S” specifies the date and time in this form:

14-04-2020 13:09:42

Following are the conversion specifiers, may be used for formatted display:

Specifier Meaning
%a The abbreviated name of the weekday as per the present locale.
%A The name of the weekday as per the present locale.
%b Name of the abbreviated month as per the present locale.
%B Name of the full month as per present locale.
%c The preferred representation of date and time for the present locale.
%d As a decimal number for the month’s day (range 01 – 31).
%H Using 24-hrs (range 00 – 23) to the hour as decimal number.
%I Using 12-hrs (range 00 – 23) to the hour as decimal number.
%j As a decimal number for the day of the year (range 001-366).
%m As a decimal number for the month (range 01 – 12).
%M The decimal number of the minute.
%p Based on the specified time value, either ‘am’ or ‘pm’ or the equivalent strings for the current locale.
%S The decimal number of the second.
%x Preferred representation of the date for the current locale, but without time.
%X Preferred representation of the time for the current locale, but without date.
%y The year is decimal but no century (range from 00 – 99).
%Y The year is decimal including century.
%Z The time zone.

Using gettimeofday in order to Measure Program Execution Time

#include <sys/time.h>
#include <stdio.h>
 
int main() {
 
  struct timeval start, end;
  gettimeofday(&start, NULL);
 
  for (int i = 0; i <1e5 ; i++) {
  }
 
  gettimeofday(&end, NULL);
  printf("Time taken to count to 10^5 is : %ld micro seconds\n",
    ((end.tv_sec * 1000000 + end.tv_usec) -
    (start.tv_sec * 1000000 + start.tv_usec)));

  return 0;
}

Output:

This example shows that how gettimeofday() function may be used for calculation of execution time of a program.

Conclusion

In this way, the gettimeofday() function might be used in Linux. For porting existing code, the gettimeofday() function may be used but in new code it should not be used. clock_gettime()  function may be used instead of gettimeofday().

About the author

Bamdeb Ghosh

Bamdeb Ghosh

Bamdeb Ghosh is having hands-on experience in Wireless networking domain.He's an expert in Wireshark capture analysis on Wireless or Wired Networking along with knowledge of Android, Bluetooth, Linux commands and python. Follow his site: wifisharks.com