How to use the gettimeofday() function

The function gettimeofday() is used to obtain the current time in seconds and microseconds.

Directions for Use:

  1. Firstly, the header file needs to be included.
  2. Create a struct variable named ‘struct timeval tv’.
  3. Call the gettimeofday() function by passing the address of a struct variable as a parameter.
  4. After the function is executed, the struct variable tv will have its tv_sec member store the current time in seconds, and its tv_usec member store the current time in microseconds.

Sample code:

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

int main() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds: %ld\n", tv.tv_sec);
    printf("Microseconds: %ld\n", tv.tv_usec);
    return 0;
}

Please pay attention to:

  1. The second parameter of the gettimeofday() function is typically passed as NULL, indicating to use the default time zone.
  2. tv_sec is an integer of type time_t, indicating the number of seconds elapsed since 00:00:00 on January 1, 1970.
  3. The tv_usec is a long integer type that represents the number of microseconds elapsed since 00:00:00 on January 1, 1970.
bannerAds