Home / Forums / Branchless programming techniques in C++ using conditional moves (CMOV) [Part 4]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

Branchless programming techniques in C++ using conditional moves (CMOV) [Part 4]

AllocMaster
Memory Arena Specialist
MEMBER
Rep: 80
Join Date: Feb 2021
Posts: 6
Thanks: 38
3y ago · Apr 1, 2023 7:21 PM
#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.
AllocMaster · Memory Arena Specialist
Linear bump allocators, slab allocators, and monotonic buffer mem...
The following users thanked AllocMaster for this post:
SpdlogSpeedy
High-Throughput Logging
VIP
Rep: 309
Join Date: Jul 2020
Posts: 6
Thanks: 55
3y ago · Apr 1, 2023 11:10 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.
SpdlogSpeedy · High-Throughput Logging
Asynchronous ring buffer loggers, formatting engines, and zero-dr...
FastIO_Wizard
I/O & Socket Streams
MEMBER
Rep: 405
Join Date: Mar 2022
Posts: 6
Thanks: 80
3y ago · Apr 3, 2023 1:10 AM
#3
Branchless algorithms on sorted data or random game entity flags boost throughput tremendously in tight loops.
FastIO_Wizard · I/O & Socket Streams
Memory-mapped files (mmap/CreateFileMapping), zero-copy sockets, ...