1

I was wondering if it is possible in any way to count for how much time in seconds the while loop ran. I want to make a loop and change variables in the function of how many seconds it was up.

Example below :

bool verif = true;
while(verif)
{
    /*
    Do some operations
    return number of seconds
    */
}
SOKA
  • 11
  • 1
  • 2
    Have a look at `std::chrono::steady_clock` – Passerby Dec 29 '21 at 03:37
  • 4
    Does this answer your question? [Measuring execution time of a function in C++](https://stackoverflow.com/questions/22387586/measuring-execution-time-of-a-function-in-c) – ytan11 Dec 29 '21 at 03:39
  • 1
    You could use std::chrono::high_precission_clock, make sure you run the code in a loop (to call it a lot of times) and always measure multiple times. However I prefer using profilers on real code, they also give you information on call dependencies so its easier to find where the real bottleneck in your code is. Also make sure your function isn't limited by memory access. Getting data to the CPU fast enough sometimes is an issue and requires a different approach to optimization. – Pepijn Kramer Dec 29 '21 at 05:07

1 Answers1

1

There are basically two, very similar ways:

  1. Use std::chrono::steady_clock::now() is the "standard" method. This can be seen here in this post. The problem with this method is that the routine now() itself has a non-negligible execution time and it has a significant jitter as well. Therefore it is recommended only to measure loops that are greater than 1 millisecond in duration.

  2. Use timestamp counters. This is architecture specific. On x86 there is a timestamp counter running on every core and an instruction to retrieve it easily. On ARM it is not that easy as you have to enable that performance counter with a kernel module prior to using it. This method is called "micro-benchmarking" and it is preferred for fast sections of code under 1 millisecond. This is described here in this answer.

  • 3
    For benchmarking purposes you can run the same code/loop several times by an outer loop to get a more exact measurement and use the steady clock. But then compiler optimizations and caching could influence the result. – Sebastian Dec 29 '21 at 03:59