Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a basic benchmark tool to xtask #471

Merged
merged 1 commit into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions xtask/src/bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

mod walk;

use anyhow::Result;
use ext4_view::Ext4;
use std::path::Path;
use std::time::SystemTime;

/// Run a simple wall-time performance benchmark.
pub fn run_bench(path: &Path, iters: u32) -> Result<()> {
bench_impl(iters, || {
// Load the filesystem and recursively walk all directories and
// files. Each file is fully read and hashed.
let ext4 = Ext4::load_from_path(path).unwrap();
let digest = walk::walk(&ext4).unwrap();
println!("filesystem hash: {digest}");
});

Ok(())
}

/// Run `f` a total of `iters` times. Measure the duration of each
/// iteration, and report statistics.
fn bench_impl<F>(iters: u32, f: F)
where
F: Fn(),
{
let mut durations = Vec::new();
for i in 1..=iters {
println!("iter {i}:");

let start = SystemTime::now();
f();
let duration = SystemTime::now().duration_since(start).unwrap();

println!("{duration:.2?}");
durations.push(duration);
}
durations.sort();

let min = durations[0];
let max = durations.last().unwrap();
let median = durations[durations.len() / 2];
println!("range: {min:.2?} - {max:.2?}");
println!("median: {median:.2?}");
}
78 changes: 78 additions & 0 deletions xtask/src/bench/walk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use ext4_view::{Ext4, Ext4Error, File, Path};
use sha2::{Digest, Sha256};

/// Walk the filesystem and create a SHA256 hash of the paths and file
/// contents.
///
/// Returning a hash ensures that none of the reads can be optimized out.
pub fn walk(fs: &Ext4) -> Result<String, Ext4Error> {
let mut hash = Sha256::new();
walk_impl(fs, Path::ROOT, &mut hash)?;
Ok(format!("{:x}", hash.finalize()))
}

fn walk_impl(
fs: &Ext4,
path: Path<'_>,
hash: &mut Sha256,
) -> Result<(), Ext4Error> {
let entry_iter = match fs.read_dir(path) {
Ok(entry_iter) => entry_iter,
Err(Ext4Error::Encrypted) => {
eprintln!("ignoring encrypted dir");
return Ok(());
}
Err(err) => return Err(err),
};

for entry in entry_iter {
let entry = entry?;
let path = entry.path();
let name = entry.file_name();
if name == "." || name == ".." {
continue;
}

// Hash the path.
hash.update(&path);

let file_type = entry.file_type()?;
if file_type.is_symlink() {
// Hash the symlink target.
let target = fs.read_link(&path)?;
hash.update(target);
} else if file_type.is_dir() {
// Recurse.
walk_impl(fs, path.as_path(), hash)?;
} else {
// Hash the file contents.
let file = fs.open(path.as_path())?;
hash_file(file, hash)?;
};
}

Ok(())
}

/// Read a file in chunks and hash it.
fn hash_file(mut file: File, hash: &mut Sha256) -> Result<(), Ext4Error> {
let mut chunk = vec![0; 4096];

loop {
let bytes_read = file.read_bytes(&mut chunk)?;
if bytes_read == 0 {
// End of file reached.
return Ok(());
}

hash.update(&chunk[..bytes_read]);
}
}
14 changes: 14 additions & 0 deletions xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

mod bench;
mod big_fs;
mod dmsetup;
mod losetup;
Expand Down Expand Up @@ -568,6 +569,16 @@ enum Action {
/// Each can be used with the `diff-walk` action to verify that the
/// library can read the whole filesystem correctly.
DownloadBigFilesystems,

/// Benchmark the library.
Bench {
/// Path of a file containing an ext4 filesystem.
path: PathBuf,

/// Number of iterations to run.
#[arg(short, long, default_value_t = 5)]
iterations: u32,
},
}

fn main() -> Result<()> {
Expand All @@ -577,5 +588,8 @@ fn main() -> Result<()> {
Action::CreateTestData => create_test_data(),
Action::DiffWalk { path } => diff_walk::diff_walk(path),
Action::DownloadBigFilesystems => big_fs::download_big_filesystems(),
Action::Bench { path, iterations } => {
bench::run_bench(path, *iterations)
}
}
}
Loading