1.纳秒级时间精度
纳秒级时间精度timespec
和int clock_gettime(clockid_t, struct timespec *)
配合使用,其中:
第一个参数clockid_t,时钟类型:
CLOCK_REALTIME
统当前时间,从1970年1.1日算起
CLOCK_MONOTONIC
系统的启动时间,不能被设置(和单片机启动后开始计时类似)
CLOCK_PROCESS_CPUTIME_ID
本进程运行时间
CLOCK_THREAD_CPUTIME_ID
本线程运行时间
第二个参数获取的时间:
struct timespec {
time_t tv_sec; // seconds
long tv_nsec; // and nanoseconds
};
其中,tv_sec当前时刻的秒数,tv_nsec当前时刻的纳秒数(表示秒数的小数点后的数字)。
2.微妙级时间精度
微妙级时间精度, timeval
和int gettimeofday(struct timeval *tv, struct timezone *tz)
配合使用,获得当前精确时间(1970年1月1日到现在的时间),其中:
第一个参数获取的时间:
struct timeval {
time_t tv_sec; // seconds
long tv_usec; // microseconds
};
其中,tv_sec当前时刻的秒数,tv_nsec当前时刻的微秒数(表示秒数的小数点后的数字)。
第二个参数为时区信息:
struct timezone{
int tz_minuteswest; //miniutes west of Greenwich
int tz_dsttime; //type of DST correction
};
返回系统设置的所在的时区的信息。
该函数和clock_gettime()
的CLOCK_REALTIME
效果相似
3.秒级精度
秒级精度,time_t
和time(time_t *t)
配合使用,获取从1970年1.1日算到现在的秒数。
4.将至今的秒数换算成日期和时间
将至今的秒数换算成日期和时间
使用struct tm* localtime_r( const time_t* timer, struct tm* result );//线程安全
其中:第一个参数为time_t为至今的秒数,可以由以上三种方式得到
第二个参数为转化后的年月日时分秒等信息结构体:
struct tm {
int tm_sec; //seconds after the minute[0-60]
int tm_min; //minutes after the hour[0-59]
int tm_hour; //hours since midnight[0-23]
int tm_mday; //day of the month[0-31]
int tm_mon; //months since January[0-11]
int tm_year; //years since 1900
int tm_wday; //days since Sunday[0-6]
int tm_yday; //days since January
int tm_isdst; //Daylight Savings Time flag
int tm_gmtoff; //offset from CUT in seconds
char *tm_zone; //timezone abbreviation
};
5.struct tm与字符串相互转化
使用strftime,将struct tm转化为字符串
函数原型:size_t strftime(char *s,size_t maxsize,char *format,conststruct tm *timeptr)
strftime函数对timeptr指向的tm结构所代表的时间和日期进行格式编排,其结果放在字符串s中。该字符串的长度被设置为(最少)maxsize个字符。格式字符串format用来对写入字符串的字符进行控制,它包含着将被传送到字符串里去的普通字符以及编排时间和日期格式的转换控制符。
例如: strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm);
也可自行使用sprintf转化,例如: printf("Current time is %d-%d-%d %d:%d:%d\n", now.tm_year + 1900, now.tm_mon + 1, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec);
使用strptime将字符串转化为struct tm
函数原型:char *strptime(const char *buf,const char*format,struct tm *timeptr)
format字符串的构建方式和strftime的format字符串完全一样,strptime返回一个指针,指向转换过程处理的最后一个字符后面的那个字符