3 ms·
More similar optimizations: https://matklad.github.io/2025/12/09/do-not-optimize-away.html https://matklad.github.io/2025/12/09/do-not-optimize-away.ht...
by gslin 10mo ago
More similar optimizations: https://matklad.github.io/2025/12/09/do-not-optimize-away.html https://matklad.github.io/2025/12/09/do-not-optimize-away.ht...
- Lvl999Noob 10mo agoCouldn't the compiler optimise this still? Make two versions of the function, one with constant folding and one without. Then at runtime, check the value of the parameter and call the corresponding version.
- saagarjha 10mo agoYes, a sufficiently smart compiler can always tell you’re doing a benchmark and delete it. It’s just unlikely.
- wging 10mo agoThe beginning of that article is slightly wrong: the compiler should compute N(N-1)/2 (and does), because the original code adds up all the numbers from 0 to N excluding N. The usual formulation in math includes the upper bound: the sum of integers from 1 to N, including N, is N(N+1)/2, so you have to replace N by (N-1) if you want a formula for the sum where the last number is N-1.