Tag Archives: optimization

int modulus(int n, int m) { return n < m ? n : n % m; }

Real Programmers will love this! (Except that they always knew…)

At CppCon’15, Chandler Carruth, lead of the Clang team at Google, gave a great talk titled Tuning C++: Benchmarks, and CPUs, and Compilers! Oh My!. The talk that is mostly live-coding and micro-benchmarking is both, informative and entertaining. Among other things, Chandler presents an optimized version of the good old modulus. Let n be a non-negative and m a positive integer. Then he proposes replacing n % m by n < m ? n : n % m because – after all – if n is less than m, there is nothing to compute.

What supposedly was meant to be a joke, proposing a dumb micro-optimization that actually makes the code run slower, turned out to be in fact an improvement. This is astonishing because it violates just about every principle we’ve learned about writing fast code. Continue reading

Advertisement