Getting an accurate execution time in C++ (micro seconds)

后端 未结 4 824
温柔的废话
温柔的废话 2020-12-13 06:37

I want to get an accurate execution time in micro seconds of my program implemented with C++. I have tried to get the execution time with clock_t but it\'s not accurate.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 07:13

    If you are using c++11 or later you could use std::chrono::high_resolution_clock.

    A simple use case :

    auto start = std::chrono::high_resolution_clock::now();
    ...
    auto elapsed = std::chrono::high_resolution_clock::now() - start;
    
    long long microseconds = std::chrono::duration_cast(elapsed).count();
    

    This solution has the advantage of being portable.


    Beware that micro-benchmarking is hard. It's very easy to measure the wrong thing (like your benchmark optimizing away), or to include page-faults in your timed region, or fail to account for CPU frequency idle vs. turbo.

    See Idiomatic way of performance evaluation? for some general tips, e.g. sanity check by testing the other one first and see if that changes which one appears faster.

提交回复
热议问题