C++统计程序运行的时间

方法很多,本文只记录两种,简单易用:
方法一:

#include 
#include 
#include 

int main() {
   clock_t start, end;
   start = clock();
   Sleep(50); //延时50ms
   end = clock();
   std::cout << "spend time:"<<end - start << "ms" << std::endl;
}

方法二:

#include 
#include 
#include 

int main() {

    auto t1 = std::chrono::steady_clock::now();
    Sleep(50); //延时50ms
    auto t2 = std::chrono::steady_clock::now();

    //秒
    double dr_s = std::chrono::duration<double>(t2 - t1).count();
    std::cout << "spend time:" << dr_s << "s" << std::endl;

    //毫秒级
    double dr_ms = std::chrono::duration<double, std::milli>(t2 - t1).count();
    std::cout << "spend time:" << dr_ms << "ms" << std::endl;

    //微妙级
    double dr_us = std::chrono::duration<double, std::micro>(t2 - t1).count();
    std::cout << "spend time:" << dr_us << "us" << std::endl;

    //纳秒级
    double dr_ns = std::chrono::duration<double, std::nano>(t2 - t1).count();
    std::cout << "spend time:" << dr_ns << "ns" << std::endl;

}

你可能感兴趣的:(c++,c++)