c函数之gettimeofday()函数获取系统时间

gettimeofday

    使用C语言编写程序需要获得当前精确时间(1970年1月1日到现在的时间),或者为执行计时,可以使用gettimeofday()函数。

函数原型:

    int gettimeofday(struct timeval*tv, struct timezone *tz);

所需头文件:

    #include

说明:

 

其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
struct timezone{int tz_minuteswest;/*格林威治时间往西方的时差*/int tz_dsttime;/*DST 时间的修正方式*/
}
timezone 参数若不使用则传入NULL即可。 而结构体timeval的定义为:
struct timeval{long int tv_sec; // 秒数long int tv_usec; // 微秒数
}

 

它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:

 

struct timeval tv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
gettimeofday(&tv_end, NULL);

 

实例:

 

#include 
#include 
#include 
int main(void) {struct timeval tv;gettimeofday(&tv, NULL);printf("   tv_usec = %ld tv_sec = %ld\n", tv.tv_usec, tv.tv_sec);for(int i = 0; i < 4; i++){gettimeofday(&tv, NULL);printf("%d) tv_usec = %ld tv_sec = %ld\n", i, tv.tv_usec, tv.tv_sec);sleep(1);}return 0;
}


注:linux运行环境下sleep()函数需要添加头文件#include

 

运行结果:


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部