Linux gettimeofday、timeradd、timercmp and example

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值