拥抱c++ chrono 抛弃 c time

  1. 获取当前UNIX时间戳(timestamp)

UNIX时间戳(timestamp):是以GMT/UTC时间「1970-01-01T00:00:00」为起点,到当前具体时间的秒数(不考虑闰秒)

    auto now_point = std::chrono::system_clock::now();

    auto new_point_s = std::chrono::time_point_cast(now_point);
    std::cout << "UTC seconds     : " << new_point_s.time_since_epoch().count() << std::endl;

    auto new_point_ms = std::chrono::time_point_cast(now_point);
    std::cout << "UTC microseconds: " << new_point_ms.time_since_epoch().count() << std::endl;

    auto new_point_us = std::chrono::time_point_cast(now_point);
    std::cout << "UTC microseconds: " << new_point_us.time_since_epoch().count() << std::endl;

    auto new_point_ns = std::chrono::time_point_cast(now_point);
    std::cout << "UTC microseconds: " << new_point_ns.time_since_epoch().count() << std::endl;

说明:

C++标准定义了3个时钟(clock)类,分别是system_clock、steady_clock、high_resolution_clock。
system_clock:来自系统实时时钟的真实时间
steady_clock:能保证其时点(time_point)绝对不会递减的时钟。而system_clock无法保证,因为系统时间可以随时调整
high_resolution_clock:这个时钟的嘀嗒周期达到了最小值,high_resolution_clock可能是system_clock或者steady_clock的别名,具体取决于编译器。

2、格式化输出

(1)C++风格 std::put_time (头文件

auto now_point = std::chrono::system_clock::now();
std::time_t ttm = std::chrono::system_clock::to_time_t(now_point);
std::stringstream ss;
ss << std::put_time(localtime(&ttm), "%Y-%m-%d %H:%M:%S");
std::cout << ss.str() << std::endl;

(2)C风格strftime (头文件

std::time_t ttmm= std::chrono::system_clock::to_time_t(now_point);
struct tm  *timeinfo = std::localtime(&ttmm);
char buf[24] = {0};
std::strftime(buf, 24, "%Y-%m-%d %H:%M:%S", timeinfo);
std::cout << buf << std::endl;

3、格式化输入

(1)C++风格 std::get_time(头文件

std::string time_str = "20230322171019";
std::istringstream ss(time_str);
struct tm time_struct;
ss >> std::get_time(&time_struct, "%Y%m%d%H%M%S");
time_t t_time = mktime(&time_struct);
auto time_point = std::chrono::system_clock::from_time_t(t_time);

(2)C风格strptime (头文件 or

std::string time_str = "20230322171019";
strptime(time_str.c_str(), "%Y%m%d%H%M%S", &time_struct);
time_t t_time = mktime(&time_struct);
auto time_point = std::chrono::system_clock::from_time_t(t_time);

4、时间戳差(计算耗时性能)

auto start = std::chrono::steady_clock::now();
sleep(1);
auto end = std::chrono::steady_clock::now();

auto diff = end - start;
std::cout << std::chrono::duration(diff).count() << "s" << std::endl;
std::cout << std::chrono::duration(diff).count() << "ms" << std::endl;
std::cout << std::chrono::duration(diff).count() << "us" << std::endl;
std::cout << std::chrono::duration(diff).count() << "ns" << std::endl;

你可能感兴趣的:(c++,c++,开发语言)