1

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++?

AdamsK
  • 33
  • 4
  • Look at the [``](https://en.cppreference.com/w/cpp/chrono) library in C++11 and later, in particular [`std::chrono::steady_clock::now()`](https://en.cppreference.com/w/cpp/chrono/steady_clock/now), [`std::chrono::duration`](https://en.cppreference.com/w/cpp/chrono/duration), [`duration_cast`](https://en.cppreference.com/w/cpp/chrono/duration/duration_cast), etc – Remy Lebeau Sep 24 '21 at 20:25

1 Answers1

2

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.

Madahin
  • 71
  • 4
  • `std::array, 2>` (or just `std::chrono::milliseconds[2][N]`) or equivalent should suffice. – Remy Lebeau Sep 24 '21 at 20:33
  • I feel that if the answer relies heavily an another answer, the proper course of action should have been to flag as duplicate. – sweenish Sep 24 '21 at 20:41