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


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.

(Note that micro-benchmarking is hard. An accurate timer is only a small part of what’s necessary to get meaningful results for short timed regions. See Idiomatic way of performance evaluation? for some more general caveats)


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<std::chrono::microseconds>(

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.

Answered By – OlivierLi

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *