function::gettimeofday_us - Linux


The gettimeofday_us() function retrieves the current time as a microsecond-resolution timestamp, represented as a 64-bit integral value in microseconds since the UNIX epoch. It provides a high-precision timing source for accurate time measurement and synchronization.


#include <time.h>
int gettimeofday_us(struct timeval_us *tv);


  • tv: A pointer to a timeval_us structure to store the returned time.

Return Value:

Returns 0 on success, or -1 on failure with errno set to indicate the error.




Example 1: Retrieve the Current Time

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

int main() {
    struct timeval_us tv;
    if (gettimeofday_us(&tv) == 0) {
        printf("Current time: %ld microseconds since the UNIX epoch\n", tv.tv_sec * 1000000 + tv.tv_usec);
    return 0;

Example 2: Calculate Time Difference

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

int main() {
    struct timeval_us start, end;
    // Perform some time-consuming task
    printf("Time elapsed: %ld microseconds\n", (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec));
    return 0;

Common Issues

  • Ensure that the time.h header is included before using gettimeofday_us().
  • Verify that the timeval_us structure is properly defined and allocated before passing it to the function.


gettimeofday_us() can be integrated with other time-related functions, such as clock() or time(), to achieve precise timing and synchronization for various applications. It can be used in conjunction with network programming, real-time systems, or scientific simulations that require accurate timing.

Related Commands

  • gettimeofday(): Obtains the current time as a second-resolution timestamp.
  • clock_gettime() and clock_getres(): Provide access to high-resolution timers and their resolution.
  • nanosleep(): Suspends the execution of the calling thread for a specified time interval.