c++获取当前秒 毫秒 微秒 纳秒时间,便于算法运行时间比较。
// 获取当前时间的时间戳
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
auto currentTime = std::chrono::system_clock::now();
auto currentTime_s = std::chrono::time_point_cast<std::chrono::seconds>(currentTime);
auto currentTime_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentTime);
auto currentTime_micro = std::chrono::time_point_cast<std::chrono::microseconds>(currentTime);
auto currentTime_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(currentTime);
auto valueS = currentTime_s.time_since_epoch().count();
auto valueMS = currentTime_ms.time_since_epoch().count();
auto valueMicroS = currentTime_micro.time_since_epoch().count();
auto valueNS = currentTime_ns.time_since_epoch().count();
std::cout << "Seconds: " << valueS << std::endl;
std::cout << "Milliseconds: " << valueMS << std::endl;
std::cout << "Microseconds: " << valueMicroS << std::endl;
std::cout << "Nanoseconds: " << valueNS << std::endl;
//std::cout << "time_s_mils_mics: " << valueS << " " << valueMS << " " << valueMicroS << std::endl;
return 0;
}
注意:
- steady_clock 是单调的时钟,相当于教练手中的秒表;只会增长,适合用于记录程序耗时;
- system_clock 是系统的时钟;因为系统的时钟可以修改;甚至可以网络对时; 所以用系统时间计算时间差可能不准。
- high_resolution_clock 是当前系统能够提供的最高精度的时钟;它也是不可以修改的。相当于 steady_clock
的高精度版本。
//如果延时、计时用此函数
#include <iostream>
#include <chrono>
int main() {
// 获取当前时间
// 转换为毫秒精度
// 获取时间戳
auto now = std::chrono::steady_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto ms = now_ms.time_since_epoch().count();
std::cout << "当前时间(毫秒精度): " << ms << " 毫秒" << std::endl;
return 0;
}