C++有关时间代码
0. 时间日期
tm结构体
/* ISO C `broken-down time' structure. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
# ifdef __USE_MISC
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
# else
long int __tm_gmtoff; /* Seconds east of UTC. */
const char *__tm_zone; /* Timezone abbreviation. */
# endif
};
栗子代码1:
#include "time.h"
#include <iostream>
int main() {
time_t now = time(0);
tm *ltm = localtime(&now);
std::cout << "year: " << 1900 + ltm->tm_year << std::endl;
std::cout << "month: " << 1 + ltm->tm_mon << std::endl;
std::cout << "day: " << ltm->tm_mday << std::endl;
std::cout << "time: " << ltm->tm_hour << std::endl;
std::cout << ltm->tm_min << ":";
std::cout << ltm->tm_sec << std::endl;
return 0;
}
栗子代码2 返回string:
std::string GetDateTimeNow() {
time_t now = time(0);
tm *ltm = localtime(&now);
std::string str = "当前时间" + std::to_string(1900 + ltm->tm_year) + "年"
+ std::to_string(1 + ltm->tm_mon) + "月"
+ std::to_string(ltm->tm_mday) + "日"
+ std::to_string(ltm->tm_hour) + "时"
+ std::to_string(ltm->tm_min) + "分";
return str;
}
1. 评估代码运行时间
#include "time.h"
#include <iostream>
int main() {
clock_t start, finish;
double duration;
start = clock();
// do sth
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
std::cout << "time : " << duration << std::endl;
return 0;
}
这里输出CLOCKS_PER_SEC等于1000000
网友评论