It’s all about Speed

When it comes to speed, everybody likes it fast. That’s why 100 m., 200m. and 4x100m. final races are the most glamorous events in Olympics – which is not to take any respect away from the long-distance runners (endurance earns respect).

And everybody loves a faster software… right?

So, as a software developer, it’s natural to think of ways to make the code more efficient and faster. Especially if the code is to run in a resource-constrained environment.

Apart from the algorithm, design and data-structure efficiency, there are a few small (language-related) things that can be done to improve the code-speed.

Before we start with the list, please note – optimization should never be the first thing on your mind… it should be the last. Once you’re sure that the code is working absolutely properly, only then start thinking about optimization.

Here we go:-

1) I don’t have a name for this one…

for (int i = 0; i < max_val; i++)
vs
for (int i = max_val – 1; i >= 0; – -i)

In the first case, to compare i with max_val, the value of max_val has to be read from the memory on each iteration.
I know some (including me) might consider it an over-kill… But I’m fond of this one. And these can matter at embedded level.

Another thing… In the second case we are using pre-increment as opposed to the post-increment. That brings me to the 2nd point.


2) If possible, always use pre-increment operator.
Prefix operator is always faster than the corresponding postfix operator.

This may not be a big thing with simple primitive types, but with bigger classes/structs, it becomes a big deal.

The post-increment operator has to keep a copy of the original to be returned.


3) temporary objects
some_class temp_heavy_func(vector<some_class> input)
{
int idx = 0;
/* do something */
return input[idx];
}

Here the first temporary is created Continue reading “It’s all about Speed”

Rules for Developing Safety Critical Code

Came across a nice paper by NASA/JPL scientist Gerard Holzmann on coding guidelines.

Fun Notes:

  • Interestingly, I recently wrote a couple of posts on the very same topics discussed in the paper – on function calls and macros – in my earlier posts. Amazing how events happen in this universe.
    🙂
  • I’ve worked on a project in which I blatantly broke the first rule – by using setjmp/longjmp to gracefully handle asserts and error-conditions.

Here’s the link to the paper The power of Ten Rules for Developing Safety Critical Code.