Home / Forums / Branchless programming techniques in C++ using conditional moves (CMOV)

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

Branchless programming techniques in C++ using conditional moves (CMOV)

TemplateTitan
Template Metaprogramming
MEMBER
Rep: 80
Join Date: Apr 2023
Posts: 6
Thanks: 49
3y ago · Apr 10, 2023 11:21 AM
#1
Branch mispredictions on modern pipelined CPUs cost 15 to 20 clock cycles. Branchless code uses arithmetic bitwise operations or ternary expressions that compile to CMOV instructions instead of jmp/je branches.
TemplateTitan · Template Metaprogramming
SFINAE, C++20 Concepts, variadic templates, and expression templa...
The following users thanked TemplateTitan for this post:
LockFreeLarry
Concurrent Systems
MEMBER
Rep: 106
Join Date: Sep 2022
Posts: 6
Thanks: 45
3y ago · Apr 10, 2023 2:49 PM
#2
For example: int maxVal = (a > b) ? a : b; compiles to a single cmp followed by cmovg on x86_64, eliminating branch misprediction penalties completely.
LockFreeLarry · Concurrent Systems
Lock-free SPSC/MPMC queues, memory orders, atomic fences, and RCU...
SmartPointerSam
C++ Memory Safety
MEMBER
Rep: 404
Join Date: May 2024
Posts: 6
Thanks: 78
3y ago · Apr 11, 2023 3:49 PM
#3
Branchless algorithms on sorted data or random game entity flags boost throughput tremendously in tight loops.
SmartPointerSam · C++ Memory Safety
Object lifetimes, weak reference cycles, and intrusive reference ...