Linux下计时函数gettimeofday()的使用

Linux下可以使用gettimeofday()来查看当前时间,这个函数会计算从1970年1月1号00:00(UTC)到当前的时间跨度。其函数原型如下,

#include <sys/time.h>

// 调用成功返回0,失败返回-1
int gettimeofday(struct timeval *tv, struct timezone *tz);

该函数所算出的时间跨度会存放在第一个参数tv里,这个参数的类型定义如下,

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

可以看出算出来的时间跨度可以精确到微妙,time_t和suseconds_t的实际类型是long int。日常使用时,只需传第一个参数,第二个参数传NULL(因为linux内核不会使用这个参数)。

举例

下面是个简单例子,计算当前时间,

#include <sys/time.h>                                                                                           
#include <stdio.h>
 
int main(void)
{
    struct timeval val;
    int ret = gettimeofday(&val, NULL);
    if (ret == -1)
    {
        printf("Error: gettimeofday()\n");
        return ret;
    }
 
    printf("sec: %ld, usec: %ld\n", val.tv_sec, val.tv_usec);
 
    return 0;
}

打印输出,
在这里插入图片描述
一般来说,我们使用gettimeofday()多是用来计算时间差,下面是计算时间差的例子,

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

 
const unsigned long Converter = 1000 * 1000; // 1s == 1000 * 1000 us

int main(void)
{
    struct timeval val;
    int ret = gettimeofday(&val, NULL);
    if (ret == -1)
    {
        printf("Error: gettimeofday()\n");
        return ret;
    }
 
    
    sleep(2); // 睡眠2s

    struct timeval newVal;
    ret = gettimeofday(&newVal, NULL);
    if (ret == -1)
    {
        printf("Error: gettimeofday()\n");
        return ret;
    }


    printf("start: sec --- %ld, usec --- %ld\n", val.tv_sec, val.tv_usec);
    printf("end:   sec --- %ld, usec --- %ld\n", newVal.tv_sec, newVal.tv_usec);

    unsigned long diff = (newVal.tv_sec * Converter + newVal.tv_usec) - (val.tv_sec * Converter + val.tv_usec);


    printf("diff:  sec --- %ld, usec --- %ld\n", diff / Converter, diff % Converter);
 
    return 0;
}

打印输出如下,
在这里插入图片描述
可以看到时间差大约是2s

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值