3 ms·
Isn't the correct way to write this loop actually: void toupper_cmov(char* buf, size_t size) { for (size_t i = 0; i < size; i++) { char c = b
by abainbridge 7y ago
Isn't the correct way to write this loop actually:
void toupper_cmov(char* buf, size_t size) {
for (size_t i = 0; i < size; i++) {
char c = buf[i];
buf[i] = c - 32 * (c >= 'a' && c <= 'z');
}
}
Because that persuades gcc and clang to transform the conditional branch into a conditional move which avoids the branch mispredict penalty and removes the need for a lookup table.
See https://godbolt.org/z/xHYKft https://godbolt.org/z/xHYKft
Disclaimer: I haven't actually run this function. That would be too much like work.
- nocturnial 7y agoWhy not use -march=native? When I look at it, I hope the compiler knows what it's doing wrt cache and whatnot. https://godbolt.org/z/zRQRkr https://godbolt.org/z/zRQRkr
- abainbridge 7y ago> Why not use -march=native? The conditional jump remains even with -march=native. https://godbolt.org/z/2p7uAB https://godbolt.org/z/2p7uAB
- nocturnial 7y agoYep just noticed it.. wanted to delete the comment but was to slow apparently