[C/C++标准库]_[初级]_[使用时间库]

来源:互联网 发布:康迪与知豆哪个好 编辑:程序博客网 时间:2024/05/22 10:54


clock

ctime

difftime

gmtime

localtime

mktime

strftime

time


场景:

1. 时间运算,显示时间等,


代码:

#include <stdlib.h>#include <time.h>#include <string.h>#include <assert.h>#include <iostream>using namespace std;void TestTime(){//time_t//For historical reasons, //it is generally implemented as an integral value representing //the number of seconds elapsed since //00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp). //Although libraries may implement this type using alternative time representations.time_t t;time(&t);//快速输出时间日期,也是静态返回.char* str_time = ctime(&t);//Www Mmm dd hh:mm:ss yyyycout << "str_time: " << str_time << endl;//1.静态返回值.//2.Coordinated Universal Time (usually Greenwich mean time), struct tm* tt = gmtime(&t);struct tm t_utc = *tt;        //1.格式化时间日期输出char str[32];memset(str,0,sizeof(str));size_t res = strftime(str,sizeof(str),"%Y-%m-%d %H:%M:%S",&t_utc);assert(res);cout << str << endl;//本地时间tt = localtime(&t);struct tm t_local = *tt;memset(str,0,sizeof(str));res = strftime(str,sizeof(str),"%Y-%m-%d %H:%M:%S",&t_local);assert(res);cout << str << endl;//1.UTC和本地时间差,秒.time_t t1 = mktime(&t_utc);time_t t2 = mktime(&t_local);double dur = difftime(t2,t1);cout << "duration seconds: " << dur  << " hours: " << dur / 3600 << endl;//1.处理器时间//The clock() function returns the processor time since the program startedclock_t c1 = clock();cout << "c1: " << c1 << endl;//转换为秒.double cs = c1 / (double)CLOCKS_PER_SEC;cout << "cs: " << cs << endl;}int main(int argc, char const *argv[]){/* code */cout << "TestFormatTime" << endl;TestTime();return 0;}

输出:

TestFormatTimestr_time: Sat Feb 08 13:43:30 20142014-02-08 05:43:302014-02-08 13:43:30duration seconds: 28800 hours: 8c1: 3cs: 0.003[Finished in 1.6s]


0 0
原创粉丝点击