我要评分
获取效率
正确性
完整性
易理解

gettimeofday

Function Usage

Obtains the current system time and returns the number of seconds and microseconds since January 1, 1970. This function is used to obtain high-precision timestamps.

Function Syntax

int gettimeofday(struct timeval *tv, struct timezone *tz);

Parameters

Parameter

Description

Value Range

Input/Output

tv

Pointer to timeval. The number of seconds and microseconds of the current time is returned.

Non-null timeval structure

Input/Output

tz

Pointer to timezone. Generally, it is not used in modern systems and is usually set to NULL.

NULL

Input

Return Value

  • Success: 0 is returned.
  • Failure: See those of open source glibc. No other exception values will be returned.

The precision of the time obtained using gettimeofday is microseconds.

Example

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

int main() {
    struct timeval tv;
    struct timezone *tz;
    int seconds;
    float micros;
    tz = NULL;
    gettimeofday(&tv, tz);
    seconds = tv.tv_sec;
    micros = tv.tv_usec;
  
    printf("Current_time (seconds): %ld\n", seconds);
    double timestamp = seconds + micros / 1.0e6;
    printf("High-precision_timestamp (seconds and microseconds): %f\n", timestamp);
    return 0;
}

Output:

Output:
Current time (seconds): ***
High-precision timestamp (seconds and microseconds): ***