Tag Archives: C++ Class for Loop Time Statistics

Histogram loop time

C++ Class for Loop Time Histogram Statistics

Overview

In this post, I am sharing a C++ Class for Loop Time Histogram. The class measures the loop time and provides its histogram statistics. It is very easy to use and portable. The class provides file output and file output + screen output features.

@Update 04/08/2020: Now histogram is printed in terminal for quick review. For details see the result picture below.

How to use

Simply include the class object, and add a function at the beginning of the loop. Finally, execute a function outputting the result.

Example Code

This example code will execute rand() function multiple times in a loop and measure its loop time.

#include <iostream>
#include <random>
#include "loop_time_stats.h"

using namespace std;

int main()
{
    loop_time_stats l("stats.txt",loop_time_stats::output_mode::fileout_and_screenout);

    for (int i=0;i<100000;i++){
        l.loop_starting_point();
        for (int j=0;j<5000;j++){
            int k =rand();
        }
    }
    l.store_loop_time_stats();
    return 0;
}

Result

C++ Class for Loop Time Histogram

The program also saves the result in a text file. I have plotted its result in Excel. The results are shown in the pictures below:

C++ Class for Loop Time Histogram

Download

You can download the class, example code, and excel files in the link below:

https://drive.google.com/drive/folders/1jMfjhO4zbqBd0Y_ozbGH7zhT0HMnUaZF?usp=sharing

Why did I develop this one?

It is critical for real-time applications to have consistent loop-times with low jitter. There are many different ways of measuring the loop time and generating the histogram (e.g., see cyclictest ( https://github.com/LITMUS-RT/cyclictest ) ), many of those are not portable.

While developing a program, these loop-time measurement codes need to be sometimes activated and sometimes deactivated. Finally they need to be removed at release. It means the code needs to be portable. Object-oriented programming (OOP) concept with C++ class is well suited for this purpose.

Thus, I have embedded all of the sophisticated-looking codes in the class and left only “init”, “loop_start_point”, and “save”. With this simple structure, the user would be easily manage the code with a minimal footage.

Reference

Good luck to your project, and if you have any questions or ideas to improve the codes, please leave a comment. Bye!