获取当前的时间的秒数和微秒数本方法需要用到gettimeofday()函数,该函数需要引入的头文件是sys/time.h 。
函数说明int gettimeofday (struct timeval * tv, struct timezone * tz)
返回值:该函数成功时返回0,失败时返回-1 参数
struct timeval{
long tv_sec;
long tv_usec;
};
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
示例
#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
附:
一秒等于1000毫秒 一秒等于1000000微秒 一秒等于1000000000纳秒