Reputation: 1
I'd like to optimize my c code which looks heavy.
Do anyone have idea to optimize below code?
// r, g, b are variables
for (x from 0 to 255)
{
for (y from 0 to 255) {
// TODO: optimize here.
arr[x][y] = (r > g) ? (r > b ? (g > b ? r - b : r - g) : b - g) : (g > b ? (r > b ? g - b : g - r) : b - r);
}
Upvotes: 0
Views: 40
Reputation: 881653
This level of optimisation is often best left to the compiler itself, which generally knows more about the target architecture than most users of the language.
The first thing it would do (or that you might do if it doesn't) is move the calculation outside of the loop.
This is, of course, assuming that code is representative and r/g/b
were constant throughout the loop, However, I suspect your code is a simplification and they are actually dependent on the loop variables.
But, you should probably optimise it first for readability, since micro-optimisations of this sort rarely deliver the performance benefits you want. It's usually far better to do macro-optimisation tasks such as more targeted data structures (trading space for time) or better algorithm selection.
Since your code appears to be getting the maximum spread of the three values (the difference between the highest and lowest), a readability optimisation could be as simple as:
// No complex expressions or side effects allowed, you've been warned!
#define ordered(a,b,c) ((a >= b) && (b >= c))
if (ordered(r,g,b)) arr[x][y] = b - r;
else if (ordered(r,b,g)) arr[x][y] = g - r;
else if (ordered(b,r,g)) arr[x][y] = g - b;
else if (ordered(b,g,r)) arr[x][y] = r - b;
else if (ordered(g,r,b)) arr[x][y] = b - g;
else /* g,b,r */ arr[x][y] = r - g;
#undef ordered
That's far more readable than that ternary monstrosity you have :-)
And, if it turns out you do need more grunt, you can revert to said code but, for the love of whatever gods you believe in (if any), comment it thoroughly to explain what it's meant to do, so the next person maintaining your code thinks kindly of you1.
And only revert if you can establish that the improvement is worth it. The prime directive of optimisation is "measure, don't guess".
1 You should always assume the coder that follows you is a psychopath who knows where you live. In my case, you'd be half right, I have no idea where you live :-)
Upvotes: 1
Reputation: 1
Also I would advise to test out if this code is really heavy or troublesome. Just assumptions can often lead to bad optimization as the used compiler may optimize especially that issue.
Upvotes: 0