Linux 時間類型與時間函數

本篇是基於APUE總結的.

時間值

UNIX以及類UNIX系統使用兩種不同的時間值.
1.日曆時間:該值是自協調世界時(UTC)1970年1月1日00:00:00這個特定時間以來所經過的秒數累計值.UTC也稱爲格林尼志標準時間.系統基本數據類型time_t用於保存這種時間值.
2.進程時間:也稱爲CPU時間,用以度量進程使用的CPU資源.進程時間以時鐘滴答計算.系統基本數據類型clock_t用於保存這種時間值.
UNIX系統爲一個進程維護了3個進程時間值:
1.時鐘時間,又稱牆上時鐘時間,它是進程運行的總時間,其值與系統中同時運行的進程數有關.
2.用戶CPU時間,指進程執行用戶指令所用的時間,即進程在用戶態的運行時間.
3.系統CPU時間,指進程執行內核程序所經歷的時間,即進程在系統態的運行時間.
進程的三種狀態:阻塞,就緒,運行.
時鐘時間=阻塞時間+就緒時間+運行時間.
運行總時間=用戶CPU時間+系統CPU時間.
在多核處理器上,若進程中有多個線程或者子進程,那麼進程的實際運行時間(時鐘時間)有可能小於運行總時間(CPU時間),因爲不同的線程或者進程可以併發執行,但其時間會計入進程的CPU總時間.

時間類型

//基本數據類型:
clock_t // 時鐘滴答的計數器
time_t // 日曆時間的秒計數器
// 複合數據類型
struct timeval {
	time_t tv_sec; // 秒
	long tv_usec; // 微秒
}
struct timespec {
	time_t tv_sec; // 秒
	long tv_nsec; // 納秒
	// 其他字段
}
struct tm { // a broekn-down time
	int tm_sec; // seconds after the minute [0-60]
	int tm_min; // minutes after the hour [0-59]
	int tm_hour; // hours after midnight [0-23]
	int tm_mday; // day of the month [1-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 1 [0-365]
	int tm_isdst; // daylight saving time flag <0, 0, >0
}

以上幾個數據類型的唯一區別是: struct tm是人類可讀的.

時間函數

#include <time.h>
timet_t time(time_t *calptr)
// 若成功,返回時間值,若出錯,返回-1
// 返回的時間值是自UTC以來的秒數.

// example1
// 參數爲空,返回自UTC以來的秒數
time_t now;
now = time(NULL);

// example2
// 參數不爲空,返回值和參數都爲UTC以來的秒數.
time_t now1, now2;
now1 = time(now2);
標識符 說明
CLOCK_REALTIME 實時系統時間
CLOCK_MONOTONIC 不帶負跳數的實時系統時間
CLOCK_PROCESS_CPUTIME_ID 調用進程的CPU時間
CLOCK_THREAD_CPUTIME_ID 調用線程的CPU時間
#include <sys/time.h>
int clock_gettime(clockid_t clock_id, struct timespec *tsp);
// 若成功返回0,若出錯返回-1
int clock_settime(clockid_t clock_id, struct timespec *tsp);
// 若成功返回0,若出錯返回-1
#include <sys/time.h>
int gettimeofday(struct timeval *tp, void * tzp);
// 函數是總是返回0
// tzp的唯一合法值是NULL
// 此函數不可移植

時間轉換函數

#include <time.h>
// gmtime將日曆時間轉換爲UTC時間
struct tm * gmtime(const time_t *calptr);
// localtime將日曆時間轉換成本地時間
struct tm * localtime(const time_t *calptr);
// mktime將本地時間轉換爲日曆時間
time_t mktime(struct tm *tmptr);
// 將分解時間打印成字符串
size_t strftime(char *buf, size_t maxsize, const char *format, const struct tm *tmptr)
// 將字符串轉換爲分解時間
char * strptime(const char *buf, const char *format, struct tm *tmptr)

各個時間函數之間的關係

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章