Skip to main content

webgraph_cli/bench/
bvgraph.rs

1/*
2 * SPDX-FileCopyrightText: 2023 Inria
3 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
4 * SPDX-FileCopyrightText: 2026 Sebastiano Vigna
5 *
6 * SPDX-License-Identifier: Apache-2.0 OR MIT
7 */
8
9use anyhow::Result;
10use clap::Parser;
11use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
12use dsi_bitstream::prelude::*;
13use itertools::Itertools;
14use lender::*;
15use rand::RngExt;
16use rand::SeedableRng;
17use rand::rngs::SmallRng;
18use std::hint::black_box;
19use std::path::PathBuf;
20use webgraph::prelude::*;
21
22#[derive(Parser, Debug)]
23#[command(name = "bvgraph", about = "Benchmarks the Rust implementation of the BV format.", long_about = None, next_line_help = true)]
24pub struct CliArgs {
25    /// The basename of the graph.​
26    pub basename: PathBuf,
27
28    /// Performs a random-access test on this number of randomly selected nodes.​
29    #[arg(short, long)]
30    pub random: Option<usize>,
31
32    /// The number of repeats.​
33    #[arg(short = 'R', long, default_value = "10")]
34    pub repeats: usize,
35
36    /// In random-access tests, test just access to the first successor.​
37    #[arg(short = 'f', long)]
38    pub first: bool,
39
40    /// Static dispatch for speed tests (default BvGraph parameters).​
41    #[arg(short = 'S', long = "static")]
42    pub _static: bool,
43
44    /// Test sequential high-speed offset/degree scanning.​
45    #[arg(short = 'd', long)]
46    pub degrees: bool,
47
48    /// Do not test speed, but check that the sequential and random-access successor lists are the same.​
49    #[arg(short = 'c', long)]
50    pub check: bool,
51
52    /// Expand offsets into a slice of usize before testing random-access
53    /// successor lists.​
54    #[arg(long)]
55    pub slice: bool,
56}
57
58pub fn main(args: CliArgs) -> Result<()> {
59    dispatch_endianness!(&args.basename, |E| match args._static {
60        true => bench_webgraph::<E, Static>(args),
61        false => bench_webgraph::<E, Dynamic>(args),
62    })
63}
64
65fn bench_random(graph: impl RandomAccessGraph, samples: usize, repeats: usize, first: bool) {
66    // Random-access speed test
67    for _ in 0..repeats {
68        let mut rng = SmallRng::seed_from_u64(0);
69        let mut c: u64 = 0;
70        let num_nodes = graph.num_nodes();
71        let start = std::time::Instant::now();
72        if first {
73            for _ in 0..samples {
74                black_box(
75                    graph
76                        .successors(rng.random_range(0..num_nodes))
77                        .into_iter()
78                        .next()
79                        .unwrap_or(0),
80                );
81                c += 1;
82            }
83        } else {
84            for _ in 0..samples {
85                c += black_box(
86                    graph
87                        .successors(rng.random_range(0..num_nodes))
88                        .into_iter()
89                        .count() as u64,
90                );
91            }
92        }
93
94        println!(
95            "{}:    {:>20} ns/arc",
96            if first { "First" } else { "Random" },
97            (start.elapsed().as_secs_f64() / c as f64) * 1e9
98        );
99    }
100}
101
102fn bench_seq(graph: impl SequentialGraph, repeats: usize) {
103    for _ in 0..repeats {
104        let mut c: u64 = 0;
105
106        let start = std::time::Instant::now();
107        let mut iter = graph.iter();
108        while let Some((_, succ)) = iter.next() {
109            c += succ.into_iter().count() as u64;
110        }
111        println!(
112            "Sequential:{:>20} ns/arc",
113            (start.elapsed().as_secs_f64() / c as f64) * 1e9
114        );
115
116        assert_eq!(c, graph.get_num_arcs().unwrap());
117    }
118}
119
120fn bench_webgraph<E: Endianness, D: Dispatch>(args: CliArgs) -> Result<()>
121where
122    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
123    for<'a> LoadModeCodesReader<'a, E, Mmap>: BitSeek,
124{
125    let (num_nodes, num_arcs, _) =
126        parse_properties::<E>(args.basename.with_extension(PROPERTIES_EXTENSION))?;
127    // Random sampling panics on an empty node range and the per-arc timings
128    // divide by the number of arcs.
129    anyhow::ensure!(
130        num_nodes > 0 && num_arcs > 0,
131        "Cannot benchmark a graph with no nodes or no arcs"
132    );
133
134    // Benchmarks random access with the given dispatch.
135    macro_rules! bench_random {
136        ($dispatch:ty, $samples:expr) => {{
137            let graph = BvGraph::with_basename(&args.basename)
138                .endianness::<E>()
139                .dispatch::<$dispatch>()
140                .mode::<Mmap>()
141                .flags(MemoryFlags::TRANSPARENT_HUGE_PAGES | MemoryFlags::RANDOM_ACCESS)
142                .load()?;
143            if args.slice {
144                bench_random(graph.offsets_to_slice(), $samples, args.repeats, args.first);
145            } else {
146                bench_random(graph, $samples, args.repeats, args.first);
147            }
148        }};
149    }
150
151    // Benchmarks sequential access with the given dispatch.
152    macro_rules! bench_seq {
153        ($dispatch:ty) => {
154            bench_seq(
155                BvGraphSeq::with_basename(&args.basename)
156                    .endianness::<E>()
157                    .dispatch::<$dispatch>()
158                    .mode::<Mmap>()
159                    .flags(MemoryFlags::TRANSPARENT_HUGE_PAGES | MemoryFlags::SEQUENTIAL)
160                    .load()?,
161                args.repeats,
162            )
163        };
164    }
165
166    if args.check {
167        let graph = BvGraph::with_basename(&args.basename)
168            .endianness::<E>()
169            .load()?;
170
171        let seq_graph = BvGraphSeq::with_basename(&args.basename)
172            .endianness::<E>()
173            .load()?;
174
175        let mut deg_reader = seq_graph.offset_deg_iter();
176
177        // Check that sequential and random-access interfaces return the same result
178        for_![ (node, seq_succ) in seq_graph {
179            let succ = graph.successors(node);
180
181            assert_eq!(deg_reader.next_degree()?, seq_succ.len());
182            assert_eq!(succ.collect_vec(), seq_succ.collect_vec());
183        }];
184    } else if args.degrees {
185        let seq_graph = BvGraphSeq::with_basename(&args.basename)
186            .endianness::<E>()
187            .load()?;
188
189        for _ in 0..args.repeats {
190            let mut deg_reader = seq_graph.offset_deg_iter();
191
192            let mut c: u64 = 0;
193            let start = std::time::Instant::now();
194            for _ in 0..seq_graph.num_nodes() {
195                c += black_box(deg_reader.next_degree()? as u64);
196            }
197            println!(
198                "Degrees Only:{:>20} ns/arc",
199                (start.elapsed().as_secs_f64() / c as f64) * 1e9
200            );
201
202            assert_eq!(c, seq_graph.get_num_arcs().unwrap());
203        }
204    } else {
205        match (
206            args.random,
207            std::any::TypeId::of::<D>() == std::any::TypeId::of::<Dynamic>(),
208        ) {
209            (Some(samples), true) => bench_random!(Dynamic, samples),
210            (Some(samples), false) => bench_random!(Static, samples),
211            (None, true) => bench_seq!(Dynamic),
212            (None, false) => bench_seq!(Static),
213        }
214    }
215    Ok(())
216}