Timing algorithm: clock() vs time() in C++

后端 未结 5 845
失恋的感觉
失恋的感觉 2020-12-22 23:08

For timing an algorithm (approximately in ms), which of these two approaches is better:

clock_t start = clock();
algorithm();
clock_t end = clock();
double t         


        
5条回答
  •  不思量自难忘°
    2020-12-22 23:41

    would be a better library if you're using C++11.

    #include 
    #include 
    #include 
    
    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();
        std::cout << "f() took "
                  << std::chrono::duration_cast(t2-t1).count()
                  << " milliseconds\n";
    }
    

    Example taken from here.

提交回复
热议问题