Branchless Programming: Difference between revisions
| (6 intermediate revisions by the same user not shown) | |||
| Line 47: | Line 47: | ||
Rather than doing | Rather than doing | ||
<syntaxhighlight lang=" | <syntaxhighlight lang="cpp"> | ||
if age > 10 | if (age > 10) { | ||
x = | x += 10; | ||
else | } else { | ||
x = | x -= 10; | ||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
you can do | you can do | ||
<syntaxhighlight lang=" | <syntaxhighlight lang="cpp"> | ||
x = x + (20 * (age > 10) - 10) | x = x + (20 * (age > 10) - 10); | ||
// or | |||
y = age > 10 | y = age > 10; | ||
x = x + 10 * y - 10 * | x = x + 10 * y - 10 * !y; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Similarly, instead of doing | Similarly, instead of doing | ||
<syntaxhighlight> | <syntaxhighlight lang="cpp"> | ||
if age > 10 | if (age > 10) { | ||
x+ | x++; | ||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
you can just write <code>x += age>10</code>. | you can just write <code>x += age>10;</code>. | ||
These are micro optimizations but they could be useful for speeding up GPU shaders in some cases. | These are micro optimizations but they could be useful for speeding up GPU shaders in some cases. | ||
In high-level programming languages such as Python, these tricks can actually slow down your code<ref name="branchless-slower-python">https://stackoverflow.com/questions/72118249/why-are-the-branchless-and-built-in-functions-slower-in-python</ref>. | |||
==Resources== | ==Resources== | ||
* [https://francescocirillo.com/pages/anti-if-campaign Anti If Campaign] | * [https://francescocirillo.com/pages/anti-if-campaign Anti If Campaign] | ||
* [https://code.joejag.com/2016/anti-if-the-missing-patterns.html Anti-If: The missing | * [https://code.joejag.com/2016/anti-if-the-missing-patterns.html Anti-If: The missing patterns] | ||
==References== | |||
<references /> | |||