歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++語言ctime庫

C++語言ctime庫

日期:2017/3/1 10:07:09   编辑:Linux編程

1. 類型
clock_t: 是個long型,用來記錄一段時間內的時鐘計時單元數,即CPU的運行單元時間。
size_t: 標准C庫中定義的,應為unsigned int,在64位系統中為long unsigned int。
time_t: 從1970年1月1日0時0分0秒到該時間點所經過的秒數。
struct tm {
int tm_sec; /* 秒 – 取值區間為[0,59] */
int tm_min; /* 分 - 取值區間為[0,59] */
int tm_hour; /* 時 - 取值區間為[0,23] */
int tm_mday; /* 一個月中的日期 - 取值區間為[1,31] */
int tm_mon; /* 月份(從一月開始,0代表一月) - 取值區間為[0,11] */
int tm_year; /* 年份,其值等於實際年份減去1900 */
int tm_wday; /* 星期 – 取值區間為[0,6],其中0代表星期天,1代表星期一,以此類推 */
int tm_yday; /* 從每年的1月1日開始的天數 – 取值區間為[0,365],其中0代表1月1日,1代表1月2日,以此類推 */
int tm_isdst; /* 夏令時標識符,實行夏令時的時候,tm_isdst為正。不實行夏令時的進候,tm_isdst為0;不了解情況時,tm_isdst()為負。*/
};
2. 時間的操作
clock: 返回時鐘計時單元數,自從這個程序開始運行。
time: 返回當前的time_t。
difftime: 計算time_t兩個之間的時間差。
3. 轉換
mktime: 轉換tm structure成time_t
asctime: 轉換tm structure成字符串
ctime: 轉換time_t成字符串
gmtime: 轉換time_t成tm as UTC time
localtime: 轉換time_t成tm as local time
strftime: 格式時間成字符串
4. 宏
CLOCKS_PER_SEC: 它用來表示一秒鐘會有多少個時鐘計時單元。

  1. // 測量事件的持續時間
  2. void test_clock_t()
  3. {
  4. long i = 100000000L;
  5. clock_t start, finish;
  6. double duration;
  7. start = clock();
  8. /* 測量一個事件持續的時間 */
  9. while(i--) {};
  10. finish = clock();
  11. duration = (double)(finish - start) / CLOCKS_PER_SEC;
  12. printf("Time to do 100000000 empty loops is %f seconds\n", duration);
  13. }
  14. void test_time_t()
  15. {
  16. time_t t = time(NULL);
  17. printf("The Calendar Time now is %d\n", t);
  18. }
  19. void test_difftime()
  20. {
  21. time_t start,end;
  22. start = time(NULL);
  23. system("pause");
  24. end = time(NULL);
  25. printf("The pause used %5.4f seconds.\n", difftime(end, start));
  26. }
  27. // 下面都是一些轉換函數的應用
  28. // mktime: tm --> time_c
  29. void test_mktime()
  30. {
  31. structtm t;
  32. time_t t_of_day;
  33. t.tm_year = 1997 - 1900;
  34. t.tm_mon = 6;
  35. t.tm_mday = 1;
  36. t.tm_hour = 0;
  37. t.tm_min = 0;
  38. t.tm_sec = 1;
  39. t.tm_wday = 4; /* Day of the week */
  40. t.tm_yday = 0; /* Does not show in asctime */
  41. t.tm_isdst = 0;
  42. t_of_day = mktime(&t);
  43. printf(ctime(&t_of_day));
  44. }
  45. // localtime: time_c --> tm
  46. void test_localtime()
  47. {
  48. time_t rawtime;
  49. structtm* timeinfo;
  50. time(&rawtime);
  51. timeinfo = localtime(&rawtime);
  52. printf("Current local time and date: %s", asctime(timeinfo));
  53. }
  54. // gmtime: time_c --> tm
  55. void test_gmtime()
  56. {
  57. time_t rawtime;
  58. structtm* timeinfo;
  59. time(&rawtime);
  60. timeinfo = gmtime(&rawtime);
  61. printf("UTC time and date: %s", asctime(timeinfo));
  62. }
  63. // ctime: time_t --> string
  64. void test_ctime()
  65. {
  66. time_t t = time(NULL);
  67. std::string str = ctime(&t);
  68. std::cout << str << std::endl;
  69. }
Copyright © Linux教程網 All Rights Reserved