C++ ctime学习笔记
在C++中,<ctime>
头文件提供了一组函数和类型,用于处理时间和日期。这些函数和类型通常用于获取当前时间、操作时间戳、进行时间和日期的格式化等操作。以下是 <ctime>
头文件的详细学习笔记:
1. time()
函数
time()
函数用于获取当前的系统时间,返回一个表示从 1970 年 1 月 1 日零时开始到现在的秒数。
示例代码:
#include <iostream>
#include <ctime>
int main() {
time_t now = time(0); // 获取当前时间
std::cout << "当前时间戳:" << now << std::endl;
return 0;
}
2. ctime()
函数
ctime()
函数将时间戳转换为字符串表示形式,返回一个表示日期和时间的字符串。
示例代码:
#include <iostream>
#include <ctime>
int main() {
time_t now = time(0); // 获取当前时间
char* dt = ctime(&now); // 将时间戳转换为字符串
std::cout << "当前时间为:" << dt << std::endl;
return 0;
}
3. gmtime()
和 localtime()
函数
gmtime()
函数将时间戳转换为格林威治标准时间(GMT)的时间结构体,而 localtime()
函数将时间戳转换为本地时间的时间结构体。
示例代码:
#include <iostream>
#include <ctime>
int main() {
time_t now = time(0); // 获取当前时间
struct tm* gmt = gmtime(&now); // 转换为 GMT 时间
struct tm* local = localtime(&now); // 转换为本地时间
std::cout << "GMT 时间:" << asctime(gmt) << std::endl;
std::cout << "本地时间:" << asctime(local) << std::endl;
return 0;
}
4. difftime()
函数
difftime()
函数用于计算两个时间点之间的差值,以秒为单位。
示例代码:
#include <iostream>
#include <ctime>
int main() {
time_t start, end;
time(&start); // 获取开始时间
// Some time-consuming operation
time(&end); // 获取结束时间
double seconds = difftime(end, start); // 计算时间差
std::cout << "操作耗时:" << seconds << " 秒" << std::endl;
return 0;
}
5. mktime()
函数
mktime()
函数将时间结构体转换为时间戳。
示例代码:
#include <iostream>
#include <ctime>
int main() {
struct tm tm;
tm.tm_year = 121; // 年份为2021
tm.tm_mon = 0; // 月份为1(从0开始计数)
tm.tm_mday = 1; // 日期为1号
time_t t = mktime(&tm); // 将时间结构体转换为时间戳
std::cout << "时间戳:" << t << std::endl;
return 0;
}
6. strftime()
函数
strftime()
函数用于将时间结构体格式化为指定格式的字符串。
示例代码:
#include <iostream>
#include <ctime>
int main() {
time_t now = time(0); // 获取当前时间
struct tm* local = localtime(&now); // 转换为本地时间
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local); // 格式化时间
std::cout << "当前时间:" << buffer << std::endl;
return 0;
}
7. clock()
函数
clock()
函数返回程序执行开始以来的时钟周期数,用于计算程序执行时间。
示例代码:
#include <iostream>
#include <ctime>
int main() {
clock_t start = clock(); // 记录开始时钟周期数
// 执行一些操作
clock_t end = clock(); // 记录结束时钟周期数
double duration = (double)(end - start) / CLOCKS_PER_SEC; // 计算执行时间(秒)
std::cout << "操作耗时:" << duration << " 秒" << std::endl;
return 0;
}
<ctime>
头文件中还包含其他一些有用的函数,如 difftime()
、mktime()
、strftime()
等,可以根据需要进一步学习和应用。