Time Acquisition Function

Catalog

The basic time provided by the Linux kernel is the number of seconds elapsed since the specific time 1970-01:00:00+0000 (UTC). This description is expressed in the data type time_t, which we call calendar time.
There are three functions to get calendar time: time, clock_gettime and gettime of day.

time function

#include <time.h>

//Successfully returning calendar time, error returning - 1; if time is not NULL, it also returns time value through it.
time_t time(time_t *time);
#include <stdio.h>
#include <string.h>
#include <time.h>

void print_time()
{
    time_t seconds = time(NULL);

    printf("seconds = %ld\n", seconds);
}

int main()
{
    print_time();

    return 0;
}

clock_gettime function

The clock_gettime function can be used to get the time of the specified clock, and the return time is saved through the struct timespec structure, which represents the time as seconds and nanoseconds.

#include <time.h>

struct timespec
{
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

//Link with -lrt.
int clock_gettime(clockid_t clock_id, struct timespec *tsp);

clock_id is generally set to CLOCK_REALTIME to obtain high-precision calendar time.

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

void print_time()
{
    time_t seconds;
    struct timespec tsp;

    seconds = time(NULL);
    printf("seconds = %ld\n", seconds);

    clock_gettime(CLOCK_REALTIME, &tsp);
    printf("tsp.tv_sec = %ld, tsp.tv_nsec = %ld\n", tsp.tv_sec, tsp.tv_nsec);
}

int main()
{
    print_time();

    return 0;
}

Gettimeoff function

Similar to the clock_gettime function, gettimeoff returns calendar time through the struct timeval structure, which represents time as seconds and subtleties.

#include <sys/time.h>

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

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

It should be noted that the only valid value of parameter tz is NULL.

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

void print_time()
{
    time_t seconds;
    struct timespec tsp;
    struct timeval tv;

    seconds = time(NULL);
    printf("seconds = %ld\n", seconds);

    clock_gettime(CLOCK_REALTIME, &tsp);
    printf("tsp.tv_sec = %ld, tsp.tv_nsec = %ld\n", tsp.tv_sec, tsp.tv_nsec);

    gettimeofday(&tv, NULL);
    printf("tv.tv_sec = %ld, tv.tv_usec = %ld\n", tv.tv_sec, tv.tv_usec);
}

int main()
{
    print_time();

    return 0;
}

Tags: Linux

Posted on Tue, 08 Oct 2019 03:09:27 -0700 by bmdsherman