UTC:世界標準時間,即格林威治標準時間(GMT);
Calendar Time:日曆時間,是用“從一個標準時間點(如:1970年1月1日0點)到此時經歷的秒數”來表示的時間。
2)時間獲取
#include <time.h>
// typedef long time_t
time_t time(time_t *tloc)
功能:獲取日曆時間,即從1970年1月1日0時到現在所經歷的秒數。
3)時間轉化
struct tm *gmtime(const time_t *timep)
功能:將日曆時間轉化爲格林威治標準時間,並保存至TM結構。
struct tm *localtime(const time_t *timep)
功能:將日曆時間轉化爲本地時間,並保存至TM結構。
4)時間保存(TM結構)
struct tm {
int tm_sec; //秒值
int tm_min; //分鐘值
int tm_hour; //小時值
int tm_mday; //本月第幾日
int tm_mon; //本年第幾月
int tm_year; //tm_year+1900=哪一年
int tm_wday; //本週第幾日
int tm_yday; //本年第幾日
int tm_isdst; //日光節約時間
}
5)例:time.c
#include<time.h>
#include<stdio.h>
int main(void) {
time_t t;
struct tm *local;
t = time(NULL);
local = localtime(&t);
printf("Local hour is: %d\n", local->tm_hour);
printf(ctime(&t));
local = gmtime(&t);
printf(asctime(local));
return 0;
}
6)時間顯示
char *asctime(const struct tm *tm)
功能:將tm格式的時間轉化爲字符串,如:
Mon Jul 28 09:25:01 2005
char *ctime(const time_t *timep)
功能:將日曆時間轉化爲本地時間的字符串形式。
6)獲取時間
int gettimeofday(struct timeval *tv, struct timezone *tz)
功能:獲取從今日凌晨到現在的時間差,常用於計算事件耗時。
struct timeval {
int tv_sec; //秒數
int tv_usec; //微秒數
}
如:計算函數function()運行時間,片段如下:
struct timeval tvstart, tvend;
float timeuse;
gettimeofday(&tvstart, NULL); //開始時間
function();
gettimeofday(&tvend, NULL); //結束時間
//計算執行時間
timeuse = 1000000*(tvend.tv_sec-tvstart.tv_sec)
+ (tvend.tv_usec-tvstart.tv_usec);
timeuse /= 1000000;
7)延時執行
unsigned int sleep(unsigned int seconds)
功能:使程序睡眠seconds秒
void usleep(unsigned long usec)
功能:使程序睡眠usec微秒