c++timectime

Recording how much time is required to run a portion of code and store it to an array in C++


Need help in recording time taken to run several parts of code in C++. I need to store these times to an array for use later. In MATLAB I would do something like this;

for i=1 : n
    tic
    this is some stuff I want to run();
    array[1,i] = toc;
   
    tic
    this is some other stuff I want to run();
    array[2,i] = toc;
end

The above would run 2 different things n times and store the time taken to individually run those things into a 2-D array.

Is there something equivalent in C++?


Solution

  • You can use std::chrono::steady_clock::now() to get the current time (tic in your exemple).

    You can find more details in this answer.

    For a 2d array, a simple std::array<T, n> where T is some kind of std::tuple should do the trick.