How to use the gettimeofday() function
The function gettimeofday() is used to obtain the current time in seconds and microseconds.
Directions for Use:
- Firstly, the header file
needs to be included. - Create a struct variable named ‘struct timeval tv’.
- Call the gettimeofday() function by passing the address of a struct variable as a parameter.
- 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:
- The second parameter of the gettimeofday() function is typically passed as NULL, indicating to use the default time zone.
- tv_sec is an integer of type time_t, indicating the number of seconds elapsed since 00:00:00 on January 1, 1970.
- The tv_usec is a long integer type that represents the number of microseconds elapsed since 00:00:00 on January 1, 1970.