Linux时间函数gettimeofday() 简介和实例测试

本文介绍了Linux系统中gettimeofday()函数的使用方法及其参数结构体timeval和timezone的细节。并通过实例展示了如何获取高精度的当前时间,并讨论了32位与64位系统上可能出现的数据类型溢出问题。

Linux时间函数gettimeofday() 简介和实例测试


一、gettimeofday

     The  functions can gives the number of seconds and microseconds since the Epoch

       获得当前精确时间(1970年1月1日到现在的时间),精度可以达到微妙。


二、相关的结构体

            1、struct  timeval

                    {

                       long  tv_sec;/*秒*/

                       long  tv_usec;/*微妙*/

                    };

            2、struct  timezone

                    {

                        int tz_minuteswest;/*和greenwich 时间差了多少分钟*/

                        int tz_dsttime;/*type of DST correction*/

                    }

            3、在gettimeofday()函数中tv或者tz都可以为空。如果为空则就不返回其对应的结构体。

            4、函数执行成功后返回0,失败后返回-1,错误代码存于errno中。


三、关于在32位机在获取时间返回负数的问题。

          long类型在32位机子上占用4个字节,在64位机子上占用8个字节,tv.tv_sec * 1000这里的计算应该没有进行类型转换,之后会得到一个溢出的负数,之后返回的时候虽然强转成了long long,但还是返回负数,为时已晚。需要先把tv.tv_sec转成long long类型,这样就不会造成溢出了。请看下面例子里面的在32位机上调用的get_current_time_32bit函数和64位机上面调用的get_current_time_64bit函数的区别。


四、linux下测试C代码:

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

long  long get_current_time_32bit(void) 
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return ((long long)tv.tv_sec) * 1000 + tv.tv_usec / 1000;
}  

unsigned long long get_current_time_64bit(void) 
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}  

int main(void) {  
    struct timeval tv; 
    int i;	
	
	printf("sizeof(long)=%ld,sizeof(unsigned long long )=%ld\n",sizeof(long),sizeof(unsigned long long ));
    gettimeofday(&tv, NULL);  
    printf("   tv_usec = %ld tv_sec = %ld\n", tv.tv_usec, tv.tv_sec);  
    for(i = 0; i < 100; i++){  
        gettimeofday(&tv, NULL);  
        printf("%d) tv_usec = %ld tv_sec = %ld\n", i, tv.tv_usec, tv.tv_sec);  
		printf("\n(64bit)current time is %lld ms\n",get_current_time_64bit());
		printf("\n(32bit)current time is %lld ms\n",get_current_time_32bit());
        sleep(1);  
    }  
    return 0;  
}  

五、测试结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值