目录
Linux下获取微秒级时间
ref:
(郝峰波) https://www.cnblogs.com/fengbohello/p/4153831.html
定义
#include <sys/time.h>
int gettimeofday(struct timeval*tv, struct timezone *tz);
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果(此处不需要tz,故使用时将其置为NULL即可)
struct timeval定义如下
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
示例
#include <stdio.h> // for printf()
#include <sys/time.h> // for gettimeofday()
#include <unistd.h> // for sleep()
int main()
{
struct timeval start, end;
gettimeofday( &start, NULL );
printf("start : %d.%d\n", start.tv_sec, start.tv_usec);
sleep(1);
gettimeofday( &end, NULL );
printf("end : %.6lf\n", end.tv_sec + end.tv_usec * 0.000001);
return 0;
}
输出
start : 1571211587.119612
end : 1571211588.119762
time_t和struct tm之间的转换
ref:
版权声明:本文为优快云博主「fulinux」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/fulinus/article/details/40083295
time_t到struct tm的转换:
#include <time.h>
struct tm *localtime(const time_t *timep);
struct tm到time_t的转换:
#include <time.h>
time_t mktime(struct tm *tm);
strptime时间字符串格式化为struct tm
ref:https://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html
定义
char *strptime(const char *restrict buf, const char *restrict format,
struct tm *restrict tm);
示例
#include <stdio.h>
#include <time.h>
int main()
{
char time[100] = "2019-10-16 16:00:00";
char time_format[100] = "%Y-%m-%d %H:%M:%S";
struct tm tm;
strptime(time, time_format, &tm);
printf("Time is %04d-%02d-%02d %02d:%02d:%02d\n", 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
return 0;
}
输出
Time is 2019-10-16 16:00:00