Linux gettimeofday、timeradd、timercmp and example

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a987860319/article/details/79970552

gettimeofday

/* 根据时域获取当前时间 */
int gettimeofday(struct timeval *tv, struct timezone *tz);

参数定义如下:

struct timeval {
   time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};
struct timezone {
   int tz_minuteswest;     /* minutes west of Greenwich */
    int tz_dsttime;         /* type of DST correction */
};

timeradd

/* a和b相加的结果放到res中 */
void timeradd(struct timeval *a, struct timeval *b,
                     struct timeval *res);

timercmp

/*
compares the timer values in a and b using the comparison operator CMP, 
and returns true (nonzero) or false (0) depending on the result 
of the comparison. Some systems (but not Linux/glibc), have a 
broken timercmp() implementation, in which CMP of >=, <=, and 
== do not work; portable applications can instead use 
*/
int timercmp(struct timeval *a, struct timeval *b, CMP);

example

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <linux/netlink.h>
#include <errno.h>
#include <sys/time.h>

int main(int argc, char const *argv[])
{
    struct timeval now, max_timeout, timeout;
    unsigned long long current, start;

    gettimeofday(&now, NULL);/* 获取当前时间 */
    max_timeout.tv_sec = 10;/* 设置10s后超时 */
    max_timeout.tv_usec = 0;
    timeradd(&now, &max_timeout, &timeout);/* 计算超时后的时间 */

    start = ((unsigned long long)now.tv_sec * 1000000LL) + now.tv_usec; /* 记录开始时的时间 */

    while (1) {
        gettimeofday(&now, NULL);
        if (timercmp(&now, &timeout, >)) {/* 比较是否超时 */
            current = ((unsigned long long)now.tv_sec * 1000000LL) + now.tv_usec;
            printf("timeout happend after %llu seconds\n", (current / 1000000) - (start / 1000000));
            break;
        } else {
            printf("no timeout...\n");
        }
        sleep(1);
    }
    return 0;
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页