1.设置休眠时间sleep_for
添加头文件
#include <thread>
#include <iostream>
#include <chrono>
#include <thread>int main(int argc, char const *argv[])
{// 休眠2秒std::this_thread::sleep_for(std::chrono::seconds(2));// 休眠500毫秒std::this_thread::sleep_for(std::chrono::milliseconds(500));// 休眠1000微妙std::this_thread::sleep_for(std::chrono::microseconds(1000));std::cout << "程序继续执行" << std::endl;return 0;
}
2.打印时间
添加头文件
#include <thread>
#include <chrono>
#Include <iomanip> 用于打印输出时间
2.1打印时间段(两个时间点的差值)
std::chrono::high_resolution_clock常用于获取精确时间的差值
auto start = std::chrono::high_resolution_clock::now();std::this_thread::sleep_for(std::chrono::seconds(2));auto stop = std::chrono::high_resolution_clock::now();std::chrono::duration<double> duration = stop - start;std::cout << "stop-start=" << duration.count() << std::endl;
2.2输出当前系统时间
要输出当前系统时间一般用std::chrono::system::clock
// 获取当前系统时间点auto now = std::chrono::system_clock::now();// 转换为time_t类型std::time_t now_c = std::chrono::system_clock::to_time_t(now);// 将time_t转换为本地时间std::tm *local_time = std::localtime(&now_c);// 格式化输出日期和时间std::cout << "当前系统时间是: " << std::put_time(local_time, "%Y-%m-%d %H:%M:%S") << std::endl;
2.3计时器
例:计算打印100次hello用了多少时间
#include <iostream>
#include <chrono>class Timer
{
public:std::chrono::time_point<std::chrono::high_resolution_clock> start, end;Timer(){start = std::chrono::high_resolution_clock::now();}~Timer(){end = std::chrono::high_resolution_clock::now();std::chrono::duration<float> duration = end - start;float ms = duration.count() * 1000.0f;std::cout << "Timer took " << ms << "ms" << std::endl;}
};
void function()
{Timer timer;for (int i = 0; i < 100; i++){std::cout << "hello\n";}
}int main(int argc, char const *argv[])
{function();return 0;
}
2.4使用c++制作简易定时器
#include <iostream>
#include <chrono>
#include <iomanip>
#include <string>class Timer
{
public:void starttime(){std::cout << "开始计时" << std::endl;start = std::chrono::high_resolution_clock::now();}void pausetime(){stop = std::chrono::high_resolution_clock::now();std::chrono::duration<double> duration = stop - start;std::cout << "计时结束" << std::endl;std::cout << "stop-start=" << duration.count() << std::endl;}void showtime(){auto now = std::chrono::system_clock::now();std::time_t now_c = std::chrono::system_clock::to_time_t(now);std::tm *local_time = std::localtime(&now_c);std::cout << "当前系统时间是:" << std::put_time(local_time, "%Y-%m-%d %H:%M:%S") << std::endl;}private:std::chrono::time_point<std::chrono::high_resolution_clock> start;std::chrono::time_point<std::chrono::high_resolution_clock> stop;
};int main(int argc, char const *argv[])
{Timer timer;char p;while (1){std::cout << "请输入字符 s:start p:pause t:showtime q:quit" << std::endl;std::cin >> p;switch (p){case 's':timer.starttime();break;case 'p':timer.pausetime();break;case 't':timer.showtime();break;case 'q':std::cout << "程序结束" << std::endl;return 0;}}return 0;
}