Marcin Zdunek Marcin Zdunek - 3 months ago 25
C Question

Introduction to dynamic loading in C++

Currently I am developing embedded application which needs to use as low CPU as possible. The main loop is writing some bits to output. Number of loop iterations is very important variable, let's call it

N
.

N
can be in range of 0 to 3.

for (int i=0; i<N; i++) {
WriteBits();
}


This approach uses
N
variable saved in config file, which is loaded during application start. This approach is very comfortable, setting
N
value needs only to replace value stored in configuration file.

But another way to code it, is to involve define macros:

#define N 3
...
WriteBits();
#if N >= 1
WriteBits();
#endif

#if N >= 2
WriteBits();
#endif

#if N == 3
WriteBits();
#endif


This method is much faster, but of course needs
N
value to be hardcoded.

Is there another approach which would let
N
variable to be loaded from file while running and insert it into
#if
statements?

My application is running on Linux Raspbian.

EDIT:

This application is used to display text on LED panels. When I use for loop method, framerate is about 145 Hz. When using defines it's getting to 200 Hz.

Answer

[To kick off, I definitely question the need to refresh a text display at 200Hz! I'm also curious as to why the loop conditional has so much impact, given that WriteBits is presumably spending 10s or 100s of cycles actually doing the update.]


One alternative approach is to have four individual functions, writeZeroBits(), writeOneBits(), etc. and call via a function pointer depending on the value of N. Assuming N changes relatively infrequently, then this avoids the conditional, but is still fully "dynamic" (at the expense of having to maintain four functions instead of one).