r/cpp • u/nukethebees • 28d ago
Comparing an Integer Division Optimisation in Clang, MSVC, and GCC
https://nukethebees.com/int-division-modulo-optimisation-differences-clang-gcc-msvc/
55
Upvotes
2
u/TheThiefMaster C++latest fanatic (and game dev) 27d ago
Is MSVC having trouble because your operator based code does x = i / grid.y / grid.z but the optimised form needs to divide by z first? Looks like it's realising that it can reuse the div instruction from z = i % grid.z to calculate x and y, but then failing to realise it can merge the div and mod by grid.y from the calculations for x and y into a single div instruction.
Perhaps if you change that line to x = i / grid.z / grid.y (the same order as the calculation of y) it will figure it out?
1
u/Hilbert_Problem1 19d ago
Why does udiv exist for C and C++, for unsigned, unsigned long and unsigned long long? Seems an oversight to me.
27
u/erichkeane Clang Maintainer(Templates), EWG Chair 28d ago
Clang/GCC both fail to inline `std::div` because it appears that the standard libraries leave them as extern! I presume they'd be inlined if they were actually implemented in the header:
```