前言:
在开发中,很多时候需要知道各个函数或者是某些设备对命令的操作用时,因此需要用到 gettimeofday 来获取当前时钟。
一,函数说明
#include
int gettimeofday(struct timeval *tv, struct timezone *tz);
注意:
1.精确级别,微妙级别
2.受系统时间修改影响
3.返回的秒数是从1970年1月1日0时0分0秒开始
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
结构体timeval的定义为:
struct timeval
{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
它获得的时间精确到微秒(1e-6 s)量级
结构体timezone的定义为:
struct timezone
{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime; /*DST 时间的修正方式*/
}
timezone 参数若不使用则传入NULL即可。
其中 tz_dsttime 的值:
DST_NONE /*不使用*/
DST_USA /*美国*/
DST_AUST /*澳洲*/
DST_WET /*西欧*/
DST_MET /*中欧*/
DST_EET /*东欧*/
DST_CAN /*加拿大*/
DST_GB /*大不列颠*/
DST_RUM /*罗马尼亚*/
DST_TUR /*土耳其*/
DST_AUSTALT /*澳洲(1986年以后)*/
//返回值:成功则返回0,失败返回-1,错误代码存于errno。
// ERRORS
// EFAULT One of tv or tz pointed outside the accessible address space.
// EINVAL Timezone (or something else) is invalid.
二,实例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
int time_substract(struct timeval *result, struct timeval *begin,struct timeval *end)
{
if(begin->tv_sec > end->tv_sec) return -1;
if((begin->tv_sec == end->tv_sec) && (begin->tv_usec > end->tv_usec)) return -2;
result->tv_sec = (end->tv_sec - begin->tv_sec);
result->tv_usec = (end->tv_usec - begin->tv_usec);
if(result->tv_usec < 0)
{
result->tv_sec--;
result->tv_usec += 1000000;
}
return 0;
}
int main(int argc, char **argv)
{
struct timeval start,stop,diff;
memset(&start,0,sizeof(struct timeval));
memset(&stop,0,sizeof(struct timeval));
memset(&diff,0,sizeof(struct timeval));
gettimeofday(&start,0);
//做你要做的事...
printf("hello world\n");
gettimeofday(&stop,0);
time_substract(&diff,&start,&stop);
printf("Total time : %d s,%d us\n",(int)diff.tv_sec,(int)diff.tv_usec);
}
获取当前的时间的秒数和微秒数本方法需要用到gettimeofday()函数,该函数需要引入的头文件是 sys/time.h 。
函数说明int gettimeofday (struct timeval * tv, struct timezone * tz)
1、返回值:该函数成功时返回0,失败时返回-1
2、参数
struct timeval{
long tv_sec; //秒
long tv_usec; //微秒
};
struct timezone
{
int tz_minuteswest; //和Greenwich 时间差了多少分钟
int tz_dsttime; //日光节约时间的状态
};
#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main(){
struct timeval tv;
memset(&tv,0,sizeof(struct timeval));
gettimeofday(&tv,NULL);
printf("second:%ld\n",tv.tv_sec); //秒
printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
sleep(3); // 为方便观看,让程序睡三秒后对比
std::cout << "3s later:" << std::endl;
memset(&tv,0,sizeof(struct timeval));
gettimeofday(&tv,NULL);
printf("second:%ld\n",tv.tv_sec); //秒
printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
return 0;
}