// 作者:Michael
// 時間:2014 - 5 -12
近期學習C++標準庫時,我發現time.h(ctime)
裏一些函數經常導致自己困惑或者是誤用,因此打算自己寫一篇文章總結下time.h(ctime)
裏函數,也算是回答自己的一些困惑,同時也希望對讀者有一點作用。
time.h是C標準函數庫中獲取時間與日期、對時間與日期數據操作及格式化的頭文件。tim.h wiki鏈接
【注】不知爲何WIKI裏有些函數我並沒有找到。
一、頭文件
頭文件包括函數定義、宏定義以及類型定義。
1.函數
// Time manipulation(時間操作)
clock_t clock(void)
double difftime(time_t end, time_t beginig)
time_t mktime(struct tm* ptm)
time_t time(time_t* timer)
// Conversion(轉換)
char *asctime(const struct tm* tmptr)
char* ctime(const time_t* timer)
struct tm* gmtime(const time_t* timer)
struct tm* localtime(const time_t* timer)
size_t strftime(char* s, size_t n, const char* format, const struct tm* tptr)
2. 宏定義CLOCKS_PER_SEC
NULL
3. 類型clock_t
:時鐘類型size_t
:無符號整形time_t
:時間類型struct tm
:時間結構體
二、用法
- 最常用的當然是計算一段代碼執行時間了,那麼需要可以用兩個函數:
clock以及time兩個函數。
使用clock函數代碼段如下:
// using clock function
// code befor calculate time
clock_t start, end;
start = clock();
// code here, for example
for( int i = 0; i < 100; i++)
;
end = clock();
printf("%f", (double)(end - start) / CLOCKS_PER_SEC;
使用time函數代碼段:
// using time function
// code befor calculate time
double sec
time_t time;
// code to do, for example
time = time(NULL);
for( int i = 0; i < 100; i++)
;
seconds = difftime( time, time());
printf("Elapsed %f seconds\n", seconds);
總結:兩個函數從精度來比較的話,推薦使用clock函數,因爲其能達到ms級精度,而time的話只能達到s級。
-
mktime函數功能功能純粹是將時間結構體變量
*ptm
轉換爲time_t變量, 至此時間操作函數則講完。 -
上面已經介紹了頭文件中變量包括
time_t``struct tm
,那麼出現一個問題:
如何將這些變量轉換成字符串呢?也就是指定一個變量,如何輸出或者存儲到文件?
庫函數裏面提供了豐富的轉換函數,包括ctime``asctime
以及strftime
。個人認爲strftime
使用概率遠遠小於前兩個。因此可以需要時查閱資料而不用過度關注此函數。
Exapmle(例子):
/* asctime example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, time, localtime, asctime */
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "The current date/time is: %s", asctime (timeinfo) );
return 0;
}
而ctime據說很有可能是通過localtime
以及上面的asctime
函數轉換實現的,即asctime(localtime(timer)
。
Tips:
ctime
顯示的是local time, 即本地時間。而不是GM時間。
Example(例子):
/* ctime example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, time, ctime */
int main ()
{
time_t rawtime;
time (&rawtime);
printf ("The current local time is: %s", ctime (&rawtime));
return 0;
}
4.
localtime
以及gmtime
這兩個函數主要是將time_t
變量轉換爲struct
tm
結構體。一個是本地時間,一個GM時間-GMT時區時間,因此比較簡單
三、總結
這篇文章主要介紹了C標準庫裏time.h的函數、宏以及變量,區分性地介紹了函數的使用。