纯C++的获取系统时间及C风格获取时间戳;C++计算耗时

1,050 阅读1分钟
    1. c++获取时间戳,转成格式化
        #include <iostream>
        #include<chrono>
        #include <string>
    
        std::string getCurrentSystemTime()
        {
                auto tt = std::chrono::system_clock::to_time_t
                (std::chrono::system_clock::now());
                struct tm* ptm = localtime(&tt);
                char date[60] = { 0 };
                sprintf(date, "%d-%02d-%02d-%02d-%02d-%02d",
                        (int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
                        (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
                return std::string(date);
        }
    
        int main()
        {
                std::string str_time = getCurrentSystemTime();
                std::cout << "str_time: " << str_time << std::endl;
                std::cin.get();
                return 0;
        }
    
    1. 最简单的单纯获取时间戳,C语言风格
    #include <time.h>
    time_t time = time(0);
    std::cout << "time = " << time << std::endl;//1631371273
    
    格式化出来
    char * strTime = ctime(&time);
    cout << "strTime = " << strTime << endl;//Thu Jun 22 17:13:07 2017
    
    算出两次时间差
    double betweenSecond = difftime(endTime, startTime);
    
    1. std::chrono计算耗时
    auto t1=std::chrono::steady_clock::now();
    //run code
    auto t2=std::chrono::steady_clock::now();
    
    //秒
    double dr_s=std::chrono::duration<double>(t2-t1).count();
    //毫秒级
    double dr_ms=std::chrono::duration<double,std::milli>(t2-t1).count();
    //微妙级
    double dr_us=std::chrono::duration<double,std::micro>(t2-t1).count();
    //纳秒级
    double dr_ns=std::chrono::duration<double,std::nano>(t2-t1).count();