Skip to content

Kim Kullings Weblog

About my stuff

Menu
  • About me & impressum
Menu

A simple benchmark timer in C++11

Posted on December 6, 2018December 6, 2018 by kimkulling

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 &amp;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 &lt; 10; ++i) {
      Timer myTimer("Test 1.1");
      for (int j = 0; i &lt; 1000000; ++i) {
        val += i;
      }
    }
  }

  {
    Timer myTimer("Test 2");
    for (int i = 0; i &lt; 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.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Connect with me

Link to my Rss Page
Link to my Twitter Page

Categories

Find older posts

©2021 Kim Kullings Weblog | Built using WordPress and Responsive Blogily theme by Superb