firefly
firefly

Reputation: 201

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

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?

Upvotes: 4

Views: 4285

Answers (2)

vsoftco
vsoftco

Reputation: 56557

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.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224964

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.

Upvotes: 6

Related Questions