Measure CPU time and wall time of a program in C ++

std::clock()measures the number of measures over the duration of your program. Does the following code calculate the processor time or the wall clock?

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 be the meaning of time?

+4
source share
2 answers

From the documentation :

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

+6
source

( ++ 14), , , :

#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;
}

, - .

+2

All Articles