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

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;  
}  

五、测试结果



版权声明:本文为qq_37858386原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。