Skip to main content

popcount_bench/
popcount_bench.rs

1//! Times the code that counts bits, for comparing builds for different x86-64 baselines.
2//!
3//! Portable x86-64 builds lack POPCNT, the instruction that counts the 1 bits in a word, so
4//! `count_ones` compiles to a sequence of bit operations. Only `Graph::from_words` uses it in a hot
5//! loop: one exclusive or and one bit count per pair of words. This program times it on three word
6//! sets, plus an ordinary search as a control that should not change. The
7//! `.github/workflows/popcount.yml` workflow builds it twice on an x86-64 runner, for the baseline
8//! and for x86-64-v2 (which has POPCNT), and compares them.
9//!
10//!     cargo run --release --example popcount_bench -- 5
11//!
12//! Prints one `RESULT <workload> <median seconds>` line per workload.
13
14use std::time::Instant;
15
16use subgraphsearch_core::generate::generate;
17use subgraphsearch_core::rng::Xoshiro;
18use subgraphsearch_core::{Graph, Model, SearchParams, search};
19
20fn median(mut times: Vec<f64>) -> f64 {
21    times.sort_by(|a, b| a.total_cmp(b));
22    times[times.len() / 2]
23}
24
25fn time<T>(rounds: usize, mut f: impl FnMut() -> T) -> f64 {
26    std::hint::black_box(f());
27    median(
28        (0..rounds)
29            .map(|_| {
30                let start = Instant::now();
31                std::hint::black_box(f());
32                start.elapsed().as_secs_f64()
33            })
34            .collect(),
35    )
36}
37
38fn main() {
39    let rounds: usize = std::env::args()
40        .nth(1)
41        .and_then(|a| a.parse().ok())
42        .unwrap_or(5);
43    let all15: Vec<u64> = (0..1u64 << 15).collect();
44    let all16: Vec<u64> = (0..1u64 << 16).collect();
45    let weight5: Vec<u64> = (0..1u64 << 18).filter(|w| w.count_ones() == 5).collect();
46    let workloads: [(&str, &[u64], &[u32]); 3] = [
47        ("from_words_all15_d1-3", &all15, &[1, 2, 3]),
48        ("from_words_weight5_len18_d1-5", &weight5, &[1, 2, 3, 4, 5]),
49        ("from_words_all16_d1-3", &all16, &[1, 2, 3]),
50    ];
51    for (name, words, distances) in workloads {
52        let t = time(rounds, || Graph::from_words(words, distances).num_edges());
53        println!("RESULT {name} {t:.4}");
54    }
55    // the control: a search, which counts no bits in its hot loop
56    let g = generate(Model::Exponential, 1000, 500, &mut Xoshiro::new(1)).expect("a random graph");
57    let mut p = SearchParams::new(100, 4950); // a 100-clique: unreachable, so every experiment makes all its moves
58    p.experiments = 32;
59    p.max_moves = 2000;
60    let t = time(rounds, || search(&g, &p).expect("a search").successes());
61    println!("RESULT search_control {t:.4}");
62}