获取当前的时间的秒数和微秒数本方法需要用到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; //日光节约时间的状态
};
其中.tv_sec是公元1970年至今的时间(换算为秒)
.tv_usec是当前秒数下的微妙数,所以将.tv_sec*1000+.tv_usec/1000可以得到当前的毫秒数
3、示例
#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main(){
struct timeval tv;
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;
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;
}
运行结果: second:1467523986 millisecond:1467523986800 microsecond:1467523986800434 3s later: second:1467523989 millisecond:1467523989800 microsecond:1467523989800697
4、附 一秒等于1000毫秒 一秒等于1000000微秒 一秒等于1000000000纳秒
装载:http://blog.youkuaiyun.com/deyuzhi/article/details/51814934