獲取當前的時間的秒數和微秒數本方法需要用到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; //日光節約時間的狀態
};
3、示例
#include
#include
#include
#include
#include
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納秒