user3575812
user3575812

Reputation: 300

how to measure running time of specific function in C++ {very accurate}

I 'm try to measuring execution of my code in C++. but that is not very accurate. Here is my code:

std::clock_t start2;
start2 = std::clock();
myFunction();
printf("time of execution: %d ms\r\n",std::clock()-start2);

but is not accurate Enough time of execution is lower then 10 ms but the result is 10 ms or 0 ms and that is not stable.

So i looking for more accurate solution. any suggestion?

Upvotes: 2

Views: 1803

Answers (1)

quantdev
quantdev

Reputation: 23793

You can use std::chrono::high_resolution_clock from the standard <chrono> header : it is supposed to represent the most accurate clock available to the implementation.

Example:

#include <iostream>
#include <chrono>

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    auto t1 = Clock::now();
    MyFunction();
    auto t2 = Clock::now();
    std::cout <<std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << '\n';
}

Notes:

  • When timing a function, consider runtime the clock N times, to compute a running average, it is much more accurate since you smooth extreme points.
  • If you can't use c++11, boost::chrono is a very good (and extremely close) alternative.

Upvotes: 6

Related Questions