获取当前的时间的秒数和微秒数本方法需要用到gettimeofday()
函数,该函数需要引入的头文件是 sys/time.h
。
// sys/time.h
struct timeval
{
long tv_sec; //秒
long tv_usec; //微秒
};
struct timezone
{
int tz_minuteswest; //格林威治时间往西方的时差,即和格林威治差了多少分钟
int tz_dsttime; //DST 时间的修正方式
};
/**
* @params struct timeval
* @params struct timezone
* @return 成功时返回0,失败时返回-1
*/
int gettimeofday (struct timeval * tv, struct timezone * tz);
#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);
printf("3s later:");
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;
}
参考文献:
- https://blog.csdn.net/li_wen01/article/details/80422340