c++调用时间
在C++中,可以使用
- time()函数:返回自1970年1月1日以来的秒数。
- localtime()函数:将time()函数返回的秒数转换为本地时间,并以struct tm结构体的形式返回。
- strftime()函数:将时间格式化为字符串。
- clock()函数:返回从程序启动到当前所使用的CPU时间(以毫秒为单位)。
- difftime()函数:计算两个时间之间的差值。
下面是一个使用这些函数的示例代码:
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
time_t now = time(0);
char* dt = ctime(&now);
std::cout << "当前时间:" << dt << std::endl;
// 将时间转换为本地时间
tm* localTime = localtime(&now);
std::cout << "年:" << 1900 + localTime->tm_year << std::endl;
std::cout << "月:" << 1 + localTime->tm_mon << std::endl;
std::cout << "日:" << localTime->tm_mday << std::endl;
std::cout << "时间:" << localTime->tm_hour << ":" << localTime->tm_min << ":" << localTime->tm_sec << std::endl;
// 格式化时间为字符串
char buffer[80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localTime);
std::cout << "格式化时间:" << buffer << std::endl;
// 计算程序运行时间
clock_t start = clock();
// 执行一些操作
clock_t end = clock();
double duration = double(end - start) / CLOCKS_PER_SEC;
std::cout << "程序运行时间:" << duration << " 秒" << std::endl;
return 0;
}
该代码首先获取当前时间,然后将其转换为本地时间,并输出年、月、日和时间。接下来,将时间格式化为字符串,并输出格式化后的时间。最后,使用clock()函数计算程序运行时间,并输出运行时间。
原文地址: https://www.cveoy.top/t/topic/i8NX 著作权归作者所有。请勿转载和采集!