使用td::chrono 计时

官方代码如下

#include <iostream>
#include <chrono>
#include <ratio>
#include <thread>
 
void f()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    f();
    auto t2 = std::chrono::high_resolution_clock::now();
 
    // 整数时长:要求 duration_cast
    auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
 
    // 小数时长:不要求 duration_cast
    std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
 
    std::cout << "f() took " << fp_ms.count() << " ms, "
              << "or " << int_ms.count() << " whole milliseconds\n";
}

 但是个人感觉还是挺麻烦的,为了方便我可能还是会使用 Qt 的 QElapsedTimer

QElapsedTimer timer;
timer.start();
func();
std::cerr<<timer.elapsed()<<endl;

 

posted @ 2022-02-16 17:05  补码  阅读(78)  评论(0编辑  收藏  举报