I just wrote a small time-measurement-class in C++11 to be able to measure the time spended in a loop. It is just a simple struct which will measure the time via RAII ( see Resource_acquisition_is_initialization ) . The time will be measured by using the std::clock() ( see std::clock-doc ) class. So this solution will work on all platforms which are supported by a c++11-compliant compiler like g++, clang or the Visual-Studio.
You can use it as follow:
#include <ctime> #include <iostream> #include <string> struct Timer { std::clock tick; std::string mName; Timer( const std::string &name ) : mName( name ) { tick = clock(); } ~Timer() { clock_t end = clock(); double elapsed_secs = double(end - tick) / CLOCKS_PER_SEC; std::cout << "Timer " << mName << ", elapsed time " <<; elapsed_secs << "\n"; } }; int main(int argc, char *argv[]) { int val(0); { Timer myTimer("Test 1"); for (int i = 0; i < 10; ++i) { Timer myTimer("Test 1.1"); for (int j = 0; i < 1000000; ++i) { val += i; } } } { Timer myTimer("Test 2"); for (int i = 0; i < 10; ++i) { val += i; } } return 0; }
The output for this program will be ( using VC2017, Windows 10 using the Cmder terminal ):
C:\projects\TimerTest\Debug λ .\TimerTest.exe Timer Test 1.1, elapsed time 0.002 Timer Test 1, elapsed time 0.009 Timer Test 2, elapsed time 0
If you want to measure how much time will be spend in one loop just put the timer inside the loop and give it a meaningful name.