Conditional Write: Two Control-Flow Styles
Question 7 / 51 • Correct so far: 0 (0 answered)
Branch Write
std::size_t filterAbove(const std::vector<int>& data,
std::vector<int>& out, int threshold) {
std::size_t n = 0;
for (int x : data) {
if (x >= threshold) out[n++] = x;
}
return n;
}
std::size_t n = filterAbove(DATA, OUTPUT, kThreshold); Branchless Write
std::size_t filterAbove(const std::vector<int>& data,
std::vector<int>& out, int threshold) {
std::size_t n = 0;
for (int x : data) {
out[n] = x;
n += (x >= threshold);
}
return n;
}
std::size_t n = filterAbove(DATA, OUTPUT, kThreshold); Shared test data (shared-setup)
constexpr int kDataSize = 32768;
constexpr int kThreshold = 128;
static std::vector<int> makeRandomData() {
std::mt19937 rng(42);
std::uniform_int_distribution<int> dist(0, 255);
std::vector<int> v(kDataSize);
for (auto& x : v) x = dist(rng);
return v;
}
static const std::vector<int> DATA = makeRandomData();
static std::vector<int> OUTPUT(kDataSize); Which snippet is faster?
Snippet B is faster on random data. Snippet A depends on a data-driven branch, so frequent mispredictions can stall the pipeline. Snippet B avoids that branch in the hot path, reducing control-flow overhead.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Branch Write | 18 us | 1.0× |
| Branchless Write | 11.4 us | 1.6× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.