5 ms·
The overly eager optimizer in me was thinking: (price > 100) * 5 + 5; yay! no branching!
by carlob 13y ago
The overly eager optimizer in me was thinking:
(price > 100) * 5 + 5;
yay! no branching!
- deleted 13y ago[deleted]
- delinka 13y agoIff in your language of choice a Boolean is always converted to a 1 or 0. In C, at least, that's not necessarily the case. That said, I'm always looking for the least branchy way of doing things.
- dbaupp 13y agoI was under the impression that the C standard does mandate that comparisons give 1 and 0 for true and false. (Other nonzero things are considered true, but a plain comparison won't return them.)
- userbinator 13y agoIt does. ISO/IEC 9899:1999, 6.5.8, p6 has this to say: "Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int."
- praptak 13y agoDoes it compile to a piece of code without any conditional jumps?
- gsg 13y agoIt's not uncommon for machines to have a branchless idiom for generating the value of a condition. For instance, in x86: cmp price, 100 setg reg movzx reg, reg lea reg, [reg + reg*4 + 5]
- userbinator 13y agocmp price, 100 cmc salc and al, 5 add al, 5 6 bytes not including comparison. "You don't get into the demoscene, the demoscene gets into you." :)
- gsg 13y agoGet out of here with your undocumented opcodes! (Neat.)
- Evgeniuz 13y ago(((price - 100) / abs(price - 100)) * 25 + 75) / 10 Here you go, simple integer math, no programming necessary :) That said, this isn't optimisation, multiplication and division aren't intrinsically better than branching.