4

std::clock() measures the number of clock ticks within the duration of your program. In the following code, does it calculate the CPU time or wall clock time?

std::clock_t start; double duration;

start = std::clock();

/* Your algorithm here */

duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

In another scenario, with the following code:

std::clock_t start;
double time;
start = std::clock();
time = start  / (double) CLOCKS_PER_SEC;

What will the value of time be?

firefly
  • 201
  • 1
  • 3
  • 11
  • This has been answered previously http://stackoverflow.com/questions/17432502/how-can-i-measure-cpu-time-and-wall-clock-time-on-both-linux-windows – ccoder83 Apr 17 '15 at 23:41

2 Answers2

6

From the documentation:

std::clock time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

In this case you can also write a simple lambda (especially simple in C++14) that measures the time taken by any callable object, like this:

#include <iostream>
#include <chrono>

auto timing = [](auto&& F, auto&&... params) // need C++14 for auto lambda parameters
{
    auto start = std::chrono::steady_clock::now();
    F(std::forward<decltype(params)>(params)...); // execute the function 
    return std::chrono::duration_cast<std::chrono::milliseconds>(
               std::chrono::steady_clock::now() - start).count();
};

void f(std::size_t numsteps) // we'll measure how long this function runs
{
    volatile std::size_t i{}; // need volatile, otherwise the compiler optimizes the loop
    for(i = 0; i < numsteps; ++i);
}

int main()
{
    auto taken = timing(f, 500'000'000); // measure the time taken to run f()
    std::cout << "Took " << taken << " milliseconds" << std::endl;

    taken = timing(f, 100'000'000); // measure again
    std::cout << "Took " << taken << " milliseconds" << std::endl;
}

You can then reuse the lambda whenever you want to time something.

vsoftco
  • 55,410
  • 12
  • 139
  • 252