zoukankan      html  css  js  c++  java
  • C++ 获取时间

     C++ 获取时间

    头文件 chrono, 命名空间 std.

    现在时间
      std::chrono::system_clock::now() 返回系统时钟的当前时间

    时钟
      std::chrono::system_clock 代表系统当前的时间, 是不稳定的时钟, 并且提供了函数可将时间点转化为 time_t 类型的值
      std::chrono::steady_clock 表示一个稳定的时钟, 所谓稳定指调用 now()时, 其值总是大于上1次.

    延迟
      std::this_thread::sleep_for() 和 std::this_thread::sleep_until()
      std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 等待 100ms

     1 #define _CRT_SECURE_NO_WARNINGS
     2 
     3 #include <iostream>
     4 #include <string>
     5 #include <sstream>
     6 #include <iomanip>
     7 #include <chrono>
     8 
     9 std::string GetTimeStr()
    10 {
    11     std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    12     time_t tt = std::chrono::system_clock::to_time_t(now);
    13     struct tm ltm = {0};
    14     localtime_s(&ltm, &tt);
    15     std::stringstream stm;
    16     stm << std::setfill('0');
    17     stm << std::setw(4) << (ltm.tm_year + 1900) << "-";
    18     stm << std::setw(2) << (ltm.tm_mon + 1) << "-";
    19     stm << std::setw(2) << (ltm.tm_mday) << " ";
    20     stm << std::setw(2) << (ltm.tm_hour) << "-";
    21     stm << std::setw(2) << (ltm.tm_min) << "-";
    22     stm << std::setw(2) << (ltm.tm_sec);
    23 
    24     return stm.str();
    25 }
    26 
    27 void mytest(void)
    28 {
    29     std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
    30 
    31     std::chrono::steady_clock::time_point tbegin = std::chrono::steady_clock::now();
    32     std::cout << GetTimeStr().c_str() << std::endl;
    33     std::chrono::steady_clock::time_point tend = std::chrono::steady_clock::now();
    34     std::chrono::milliseconds used = std::chrono::duration_cast<std::chrono::milliseconds>(tend - tbegin);
    35     std::cout << used.count() << "ms" << std::endl;
    36 
    37     std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
    38 }
    39 
    40 int main(int argc, char * argv[], char * envp[])
    41 {
    42     mytest();
    43 
    44     system("pause");
    45     return 0;
    46 }

    运行结果:

  • 相关阅读:
    借用构造函数实现继承
    原型链
    创建对象 之 组合使用构造函数模式和原型模式
    6.原型对象的问题
    Spring MVC
    AOP
    谈谈对Spring IOC的理解
    Mybatis3.x与Spring4.x整合(转)
    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)
    Appweb写法
  • 原文地址:https://www.cnblogs.com/lsgxeva/p/7668930.html
Copyright © 2011-2022 走看看