Merge pull request #63 from huntharo/perf/scan-admission-budget

feat: add saved Power Efficiency scan worker presets (3% faster, 53% less CPU at 8 threads)
This commit is contained in:
Tobias Lütke
2026-10-01 21:45:54 -04:00
committed by GitHub
15 changed files with 2116 additions and 15 deletions
Generated
+1
View File
@@ -1440,6 +1440,7 @@ dependencies = [
"rayon",
"rustc-hash 2.1.3",
"rustix",
"sysinfo",
"tempfile",
"trash",
"winapi-util",
+1 -1
View File
@@ -20,6 +20,7 @@ disktree-core = { workspace = true }
anyhow = { workspace = true }
dunce = "1.0.5"
rustc-hash = { workspace = true }
tempfile = "3"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_System_Console"] }
@@ -30,4 +31,3 @@ gpui-kit = { version = "=0.6.6", default-features = false, features = [
"assets",
"test-support",
] }
tempfile = "3"
+204 -5
View File
@@ -16,6 +16,7 @@ mod appearance;
mod git;
mod marks;
mod palette;
mod power;
mod state;
#[cfg(test)]
mod tests;
@@ -43,6 +44,7 @@ struct Args {
root: PathBuf,
options: ScanOptions,
depth: u32,
power: Option<power::PowerEfficiency>,
}
const USAGE: &str = "\
@@ -65,6 +67,16 @@ options:
also measure other disks, network shares and pseudo
filesystems mounted below PATH (off by default)
-d, --depth N how many levels to draw at once (1-6, default 3)
--power-efficiency PRESET
miser, balanced (default), aggressive, drain-my-battery
--scan-threads N fixed scan workers, capped by available CPU count
--adaptive-threads
experimental adaptive admission (opt-in)
--fixed-threads disable adaptive admission and CPU governor
--thread-throughput-percent N
retain this percent of sampled initial throughput (80)
--thread-system-cpu-percent N
best-effort host CPU budget; 0 disables it (80)
--metric files rank by file count instead of bytes
-h, --help show this help
";
@@ -79,7 +91,16 @@ fn main() -> Result<()> {
}
fn run() -> Result<()> {
let args = parse_args(std::env::args_os().skip(1))?;
let saved = power::settings_path()
.map_or_else(
|| Ok(power::PowerEfficiency::default()),
|path| power::load(&path),
)
.unwrap_or_else(|error| {
eprintln!("Cannot load Power Efficiency: {error}; using Balanced");
power::PowerEfficiency::default()
});
let args = parse_args_with_power(std::env::args_os().skip(1), saved)?;
// When the app executable is reached through the command-line symlink,
// cmux sends SIGTERM to its foreground process group as AppKit takes
@@ -158,12 +179,14 @@ fn run() -> Result<()> {
appearance::follow(window);
}
cx.new(|cx| {
Disktree::new(
let mut app = Disktree::new(
root_for_app.clone(),
options.clone(),
depth,
cx,
)
);
app.power_choice = args.power;
app
})
},
)
@@ -181,11 +204,21 @@ fn run() -> Result<()> {
}
/// Read the command line, program name already skipped.
fn parse_args(
#[cfg(test)]
fn parse_args(args: impl Iterator<Item = std::ffi::OsString>) -> Result<Args> {
parse_args_with_power(args, power::PowerEfficiency::default())
}
fn parse_args_with_power(
mut args: impl Iterator<Item = std::ffi::OsString>,
preset: power::PowerEfficiency,
) -> Result<Args> {
let mut root: Option<PathBuf> = None;
let mut options = ScanOptions::default();
let mut options = ScanOptions {
threads: preset.policy(power::cpu_threads()),
..ScanOptions::default()
};
let mut power = Some(preset);
let mut depth = 3_u32;
let mut disk = false;
// `std::env::args` panics on a name that is not Unicode, and a path is
@@ -219,6 +252,60 @@ fn parse_args(
"--depth must be 1 to 6"
);
}
"--power-efficiency" => {
let value =
text(args.next(), "--power-efficiency needs a preset")?;
let preset = power::PowerEfficiency::parse(&value)
.context("unknown Power Efficiency preset")?;
options.threads = preset.policy(power::cpu_threads());
power = Some(preset);
}
"--scan-threads" => {
power = None;
let value = text(args.next(), "--scan-threads needs a number")?;
options.threads.max_threads = value
.parse()
.context("--scan-threads needs a positive integer")?;
anyhow::ensure!(
options.threads.max_threads > 0,
"--scan-threads must be positive"
);
}
"--fixed-threads" => {
options.threads.adaptive = false;
power = None;
}
"--adaptive-threads" => {
options.threads.adaptive = true;
options.threads.system_cpu_limit = Some(0.80);
power = None;
}
"--thread-throughput-percent" => {
let value = text(
args.next(),
"--thread-throughput-percent needs a number",
)?;
let percent: u8 = value
.parse()
.context("throughput percent must be 1 to 100")?;
anyhow::ensure!(
(1..=100).contains(&percent),
"throughput percent must be 1 to 100"
);
options.threads.retained_throughput =
f64::from(percent) / 100.0;
}
"--thread-system-cpu-percent" => {
let value = text(
args.next(),
"--thread-system-cpu-percent needs a number",
)?;
let percent: u8 =
value.parse().context("CPU percent must be 0 to 100")?;
anyhow::ensure!(percent <= 100, "CPU percent must be 0 to 100");
options.threads.system_cpu_limit =
(percent > 0).then(|| f64::from(percent) / 100.0);
}
"--metric" => {
let value = text(args.next(), "--metric needs a value")?;
options.metric = match value.as_str() {
@@ -269,6 +356,7 @@ fn parse_args(
root,
options,
depth: depth.clamp(1, 6),
power,
})
}
@@ -303,3 +391,114 @@ mod console {
}
}
}
#[cfg(test)]
mod argument_tests {
use super::*;
fn arguments(extra: &[&str]) -> impl Iterator<Item = std::ffi::OsString> {
extra
.iter()
.copied()
.chain(std::iter::once("."))
.map(std::ffi::OsString::from)
}
#[test]
fn adaptive_budget_and_fixed_override_are_explicit() {
let args = parse_args(arguments(&[])).expect("defaults");
assert_eq!(
args.options.threads.max_threads,
4.min(power::cpu_threads())
);
assert!(!args.options.threads.adaptive);
let args = parse_args(arguments(&[
"--scan-threads",
"4",
"--fixed-threads",
"--thread-throughput-percent",
"85",
"--thread-system-cpu-percent",
"0",
]))
.expect("custom");
assert_eq!(args.options.threads.max_threads, 4);
assert!(!args.options.threads.adaptive);
assert!(
(args.options.threads.retained_throughput - 0.85).abs()
< f64::EPSILON
);
assert_eq!(args.options.threads.system_cpu_limit, None);
}
#[test]
fn saved_power_is_loaded_before_cli_overrides() {
use power::PowerEfficiency as Power;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("power-efficiency");
power::save(&path, Power::Miser).expect("save");
let saved = power::load(&path).expect("load");
let args = parse_args_with_power(arguments(&[]), saved).expect("saved");
assert_eq!(args.power, Some(Power::Miser));
assert_eq!(
args.options.threads.max_threads,
2.min(power::cpu_threads())
);
let args = parse_args_with_power(
arguments(&["--power-efficiency", "drain-my-battery"]),
saved,
)
.expect("override");
assert_eq!(args.power, Some(Power::DrainMyBattery));
assert_eq!(args.options.threads.max_threads, power::cpu_threads());
let args = parse_args_with_power(
arguments(&["--scan-threads", "8", "--adaptive-threads"]),
saved,
)
.expect("experiment");
assert!(args.power.is_none());
assert!(args.options.threads.adaptive);
assert_eq!(args.options.threads.max_threads, 8);
assert_eq!(power::load(&path).expect("unchanged"), saved);
assert!(
parse_args(arguments(&["--power-efficiency", "invalid"])).is_err()
);
}
// APFS rejects these filename bytes; Linux filesystems permit them.
#[cfg(target_os = "linux")]
#[test]
fn worker_options_preserve_a_non_unicode_root() {
use std::os::unix::ffi::OsStringExt as _;
let temp = tempfile::TempDir::new().expect("tempdir");
let root = temp
.path()
.join(std::ffi::OsString::from_vec(vec![b'r', 0xff]));
std::fs::create_dir(&root).expect("directory");
let args = parse_args(
[
std::ffi::OsString::from("--scan-threads"),
std::ffi::OsString::from("4"),
root.clone().into_os_string(),
]
.into_iter(),
)
.expect("native path");
assert_eq!(args.root, dunce::canonicalize(root).expect("root"));
assert_eq!(args.options.threads.max_threads, 4);
}
#[test]
fn invalid_worker_budgets_are_rejected() {
for extra in [
vec!["--scan-threads", "0"],
vec!["--scan-threads", "-1"],
vec!["--thread-throughput-percent", "0"],
vec!["--thread-throughput-percent", "101"],
vec!["--thread-system-cpu-percent", "101"],
] {
assert!(parse_args(arguments(&extra)).is_err());
}
}
}
+207
View File
@@ -0,0 +1,207 @@
//! Saved fixed worker presets. Read before the first scan starts.
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use disktree_core::scan_threads::ScanThreads;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PowerEfficiency {
Miser,
#[default]
Balanced,
Aggressive,
DrainMyBattery,
}
impl PowerEfficiency {
pub const ALL: [Self; 4] = [
Self::Miser,
Self::Balanced,
Self::Aggressive,
Self::DrainMyBattery,
];
pub const fn key(self) -> &'static str {
match self {
Self::Miser => "miser",
Self::Balanced => "balanced",
Self::Aggressive => "aggressive",
Self::DrainMyBattery => "drain-my-battery",
}
}
pub const fn name(self) -> &'static str {
match self {
Self::Miser => "Miser",
Self::Balanced => "Balanced",
Self::Aggressive => "Aggressive",
Self::DrainMyBattery => "Drain My Battery",
}
}
pub fn parse(value: &str) -> Option<Self> {
Self::ALL.into_iter().find(|preset| preset.key() == value)
}
pub fn threads(self, cpus: usize) -> usize {
let cpus = cpus.max(1);
match self {
Self::Miser => 2.min(cpus),
Self::Balanced => 4.min(cpus),
Self::Aggressive => 8.min(cpus),
Self::DrainMyBattery => cpus,
}
}
pub fn label(self, cpus: usize) -> String {
format!("{} ({})", self.name(), workers(self.threads(cpus)))
}
/// A preset that would run no more workers than the one below it, on a
/// machine with this many CPUs, is a duplicate there and is not offered.
pub fn available(self, cpus: usize) -> bool {
// Declared in `ALL` order, so the discriminant is the index.
let index = self as usize;
index == 0 || self.threads(cpus) > Self::ALL[index - 1].threads(cpus)
}
/// How many of the four gauge bars `threads` workers fill: the presets
/// offered here that run no more than that, so a custom count reads on
/// the same scale.
pub fn signal(threads: usize, cpus: usize) -> usize {
Self::ALL
.into_iter()
.filter(|preset| {
preset.available(cpus) && preset.threads(cpus) <= threads
})
.count()
.max(1)
}
pub fn policy(self, cpus: usize) -> ScanThreads {
ScanThreads {
max_threads: self.threads(cpus),
adaptive: false,
system_cpu_limit: None,
..ScanThreads::default()
}
}
}
pub fn workers(count: usize) -> String {
let unit = if count == 1 { "worker" } else { "workers" };
format!("{count} {unit}")
}
pub fn cpu_threads() -> usize {
std::thread::available_parallelism().map_or(1, usize::from)
}
/// Follow each desktop's user configuration location; never write beside
/// the executable or scanned root. No home/config location means session-only.
pub fn settings_path() -> Option<PathBuf> {
let home = std::env::home_dir();
let base = if cfg!(target_os = "macos") {
home.map(|home| home.join("Library/Application Support"))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(PathBuf::from)
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.or_else(|| home.map(|home| home.join(".config")))
};
base.map(|base| base.join("disktree/power-efficiency"))
}
pub fn load(path: &Path) -> io::Result<PowerEfficiency> {
match std::fs::read_to_string(path) {
Ok(value) => PowerEfficiency::parse(value.trim()).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "unknown power preset")
}),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
Ok(PowerEfficiency::default())
}
Err(error) => Err(error),
}
}
pub fn save(path: &Path, preset: PowerEfficiency) -> io::Result<()> {
let parent = path.parent().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "no settings directory")
})?;
std::fs::create_dir_all(parent)?;
// Atomic replacement leaves the previous choice intact after a failed
// write, and readers never see a half-written setting.
let mut file = tempfile::NamedTempFile::new_in(parent)?;
writeln!(file, "{}", preset.key())?;
file.persist(path).map_err(|error| error.error)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presets_are_fixed_and_show_the_effective_cpu_limit() {
for (preset, expected) in
PowerEfficiency::ALL.into_iter().zip([2, 4, 8, 18])
{
let policy = preset.policy(18);
assert_eq!(policy.max_threads, expected);
assert!(!policy.adaptive);
assert_eq!(policy.system_cpu_limit, None);
assert_eq!(preset.threads(1), 1);
}
assert_eq!(PowerEfficiency::Balanced.threads(3), 3);
assert_eq!(
PowerEfficiency::DrainMyBattery.label(18),
"Drain My Battery (18 workers)"
);
}
#[test]
fn presets_that_add_no_workers_are_not_offered() {
use PowerEfficiency as P;
let offered = |cpus| {
P::ALL
.into_iter()
.filter(|preset| preset.available(cpus))
.collect::<Vec<_>>()
};
assert_eq!(offered(18), P::ALL);
assert_eq!(offered(10), P::ALL);
assert_eq!(offered(8), [P::Miser, P::Balanced, P::Aggressive]);
assert_eq!(offered(6), [P::Miser, P::Balanced, P::Aggressive]);
assert_eq!(offered(4), [P::Miser, P::Balanced]);
assert_eq!(offered(3), [P::Miser, P::Balanced]);
assert_eq!(offered(2), [P::Miser]);
assert_eq!(offered(1), [P::Miser]);
// The gauge counts what is offered, so a small machine running
// everything it has reads as full as the menu allows.
assert_eq!(P::signal(4, 18), 2);
assert_eq!(P::signal(18, 18), 4);
assert_eq!(P::signal(4, 4), 2);
assert_eq!(P::signal(1, 18), 1);
assert_eq!(P::signal(12, 18), 3);
}
#[test]
fn saved_choice_survives_replacement_and_bad_data_is_reported() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("config/power-efficiency");
assert_eq!(load(&path).expect("missing"), PowerEfficiency::Balanced);
for preset in PowerEfficiency::ALL {
save(&path, preset).expect("save");
assert_eq!(load(&path).expect("load"), preset);
}
std::fs::write(&path, "not-a-preset").expect("corrupt");
assert_eq!(
load(&path).expect_err("invalid").kind(),
io::ErrorKind::InvalidData
);
assert!(save(dir.path(), PowerEfficiency::Miser).is_err());
}
}
+142 -1
View File
@@ -327,6 +327,15 @@ pub struct Disktree {
pub root_path: PathBuf,
pub home: Option<PathBuf>,
pub options: ScanOptions,
pub power_choice: Option<crate::power::PowerEfficiency>,
pub power_settings_path: Option<PathBuf>,
/// The Power Efficiency menu, when open: the row the arrow keys are on,
/// as an index into [`crate::power::PowerEfficiency::ALL`].
pub power_menu: Option<usize>,
/// The pointer is on the menu's button. A press there is the button's
/// to toggle, not a press outside the menu that closes it first.
pub power_hover: bool,
pub cpu_threads: usize,
pub tree: Option<Arc<Node>>,
pub scan: Option<ScanHandle>,
pub scan_epoch: u64,
@@ -462,6 +471,11 @@ impl Disktree {
root_path,
home,
options,
power_choice: None,
power_settings_path: crate::power::settings_path(),
power_menu: None,
power_hover: false,
cpu_threads: crate::power::cpu_threads(),
tree: None,
scan: None,
scan_epoch: 0,
@@ -799,6 +813,108 @@ impl Disktree {
cx.notify();
}
/// Changing resource policy leaves the current scan and result intact;
/// rescan, navigation to a new root and restart use the new fixed budget.
pub fn set_power_efficiency(
&mut self,
preset: crate::power::PowerEfficiency,
cx: &mut Context<'_, Self>,
) {
self.power_menu = None;
// Not offered here: it would run the same workers as the preset
// below it, under a name that promises more.
if !preset.available(self.cpu_threads) {
cx.notify();
return;
}
self.options.threads = preset.policy(self.cpu_threads);
self.power_choice = Some(preset);
let label = preset.label(self.cpu_threads);
self.notice = Some(match self.power_settings_path.as_deref() {
Some(path) => match crate::power::save(path, preset) {
Ok(()) => (
format!("{label} from the next scan; r rescans now"),
Status::Success,
),
Err(error) => (
format!(
"{label} from the next scan, but it could not be \
saved: {error}"
),
Status::Warning,
),
},
None => (
format!(
"{label} from the next scan; no settings directory to \
save it in"
),
Status::Warning,
),
});
cx.notify();
}
/// Open the Power Efficiency menu on the current preset, or close it.
pub fn toggle_power_menu(&mut self, cx: &mut Context<'_, Self>) {
use crate::power::PowerEfficiency;
self.power_menu = if self.power_menu.is_some() {
None
} else {
// On the current preset, or the nearest one below it that this
// machine offers: a custom count starts from Balanced.
let current = self.power_choice.unwrap_or_default() as usize;
(0..=current)
.rev()
.find(|&index| {
PowerEfficiency::ALL[index].available(self.cpu_threads)
})
.or(Some(0))
};
cx.notify();
}
/// Keys while the Power Efficiency menu is open, as the sibling menu
/// takes them. The arrows step over presets this machine cannot offer.
fn on_power_key(&mut self, key: &str, cx: &mut Context<'_, Self>) -> bool {
use crate::power::PowerEfficiency;
let Some(highlighted) = self.power_menu else {
return false;
};
let cpus = self.cpu_threads;
let offered: Vec<usize> = (0..PowerEfficiency::ALL.len())
.filter(|&index| PowerEfficiency::ALL[index].available(cpus))
.collect();
let step = |forward: bool| {
let next = if forward {
offered.iter().find(|&&index| index > highlighted)
} else {
offered.iter().rev().find(|&&index| index < highlighted)
};
next.copied().unwrap_or(highlighted)
};
match key {
"down" | "j" => self.power_menu = Some(step(true)),
"up" | "k" => self.power_menu = Some(step(false)),
"home" => self.power_menu = offered.first().copied(),
"end" => self.power_menu = offered.last().copied(),
"enter" | "space" => {
self.set_power_efficiency(
PowerEfficiency::ALL[highlighted],
cx,
);
}
"escape" => self.power_menu = None,
_ => {
self.power_menu = None;
cx.notify();
return false;
}
}
cx.notify();
true
}
/// Start a fresh scan, abandoning any walk still in progress.
pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) {
if let Some(scan) = &self.scan {
@@ -2449,6 +2565,9 @@ impl Disktree {
if self.crumb_menu.is_some() && self.on_menu_key(key, cx) {
return;
}
if self.power_menu.is_some() && self.on_power_key(key, cx) {
return;
}
if self.show_help {
if matches!(key, "escape" | "?" | "/" | "q") {
@@ -2935,8 +3054,11 @@ impl Disktree {
} else {
&self.root_path
};
let args =
let mut args =
restart_args(&self.options, self.layout_options.max_depth, root);
if let Some(preset) = self.power_choice {
args.extend(["--power-efficiency".into(), preset.key().into()]);
}
// Off the UI thread: the prompt runs its own message loop, which
// would re-enter this window while it is still being handled.
let restart = cx.background_executor().spawn(async move {
@@ -2982,6 +3104,25 @@ pub fn restart_args(
if options.metric == Metric::Files {
args.push("files".into());
}
args.push("--scan-threads".into());
args.push(options.threads.max_threads.to_string().into());
args.push(if options.threads.adaptive {
"--adaptive-threads".into()
} else {
"--fixed-threads".into()
});
args.push("--thread-throughput-percent".into());
args.push(
format!("{:.0}", options.threads.retained_throughput * 100.0).into(),
);
args.push("--thread-system-cpu-percent".into());
args.push(
format!(
"{:.0}",
options.threads.system_cpu_limit.unwrap_or(0.0) * 100.0
)
.into(),
);
args.push("--depth".into());
args.push(depth.to_string().into());
args.push(root.as_os_str().to_owned());
+142
View File
@@ -1614,6 +1614,12 @@ fn restart_arguments_parse_back_to_the_same_scan() {
include_hidden: false,
one_filesystem: false,
metric: Metric::Files,
threads: disktree_core::scan_threads::ScanThreads {
max_threads: 8,
adaptive: true,
retained_throughput: 0.85,
system_cpu_limit: Some(0.70),
},
..ScanOptions::default()
};
for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] {
@@ -1622,6 +1628,18 @@ fn restart_arguments_parse_back_to_the_same_scan() {
assert_eq!(parsed.root, root);
assert_eq!(parsed.depth, depth);
let got = &parsed.options;
assert_eq!(got.threads.max_threads, options.threads.max_threads);
assert_eq!(got.threads.adaptive, options.threads.adaptive);
assert!(
(got.threads.retained_throughput
- options.threads.retained_throughput)
.abs()
< f64::EPSILON
);
assert_eq!(
got.threads.system_cpu_limit,
options.threads.system_cpu_limit
);
assert_eq!(
(
got.apparent_size,
@@ -1640,3 +1658,127 @@ fn restart_arguments_parse_back_to_the_same_scan() {
);
}
}
#[gpui_kit::test]
fn power_efficiency_menu_saves_without_discarding_the_tree(
cx: &mut TestAppContext,
) {
use crate::power::{self, PowerEfficiency as Power};
use gpui_kit::Modifiers;
cx.update(gpui_omarchy::init);
let temp = fixture();
let config = tempfile::tempdir().expect("config");
let path = config.path().join("power-efficiency");
let (view, cx) = view_over(temp.path(), cx);
cx.simulate_resize(gpui_kit::size(px(900.), px(600.)));
update(&view, cx, |app, _| {
app.power_settings_path = Some(path.clone());
// Enough CPUs that every preset is offered, whatever runs the test.
app.cpu_threads = 18;
});
let epoch = read(&view, cx, |app| app.scan_epoch);
for preset in Power::ALL {
draw(cx);
let button = cx.debug_bounds("power-efficiency").expect("control");
cx.simulate_click(button.center(), Modifiers::none());
draw(cx);
let choice = cx.debug_bounds(preset.key()).expect("preset");
cx.simulate_click(choice.center(), Modifiers::none());
draw(cx);
assert_eq!(power::load(&path).expect("saved"), preset);
read(&view, cx, |app| {
assert_eq!(app.power_choice, Some(preset));
assert_eq!(
app.options.threads.max_threads,
preset.threads(app.cpu_threads)
);
assert!(!app.options.threads.adaptive);
assert!(app.power_menu.is_none());
assert_eq!(app.scan_epoch, epoch);
assert!(app.tree.is_some());
});
}
// Persistence failure must not masquerade as a saved preference.
update(&view, cx, |app, cx| {
app.power_settings_path = Some(config.path().to_owned());
app.set_power_efficiency(Power::Miser, cx);
});
assert!(read(&view, cx, |app| app.notice.as_ref().is_some_and(
|(message, _)| message.contains("could not be saved")
)));
update(&view, cx, Disktree::start_scan);
assert_eq!(read(&view, cx, |app| app.scan_epoch), epoch + 1);
}
#[gpui_kit::test]
fn the_power_menu_offers_only_what_the_cpus_can_tell_apart(
cx: &mut TestAppContext,
) {
use crate::power::PowerEfficiency as Power;
use gpui_kit::Modifiers;
cx.update(gpui_omarchy::init);
let temp = fixture();
let config = tempfile::tempdir().expect("config");
let (view, cx) = view_over(temp.path(), cx);
cx.simulate_resize(gpui_kit::size(px(900.), px(600.)));
update(&view, cx, |app, _| {
app.power_settings_path = Some(config.path().join("power"));
// Aggressive and Drain My Battery would both run four workers.
app.cpu_threads = 4;
app.power_choice = Some(Power::Balanced);
});
draw(cx);
let toggle = cx.debug_bounds("power-efficiency").expect("control");
cx.simulate_mouse_move(toggle.center(), None, Modifiers::none());
cx.simulate_click(toggle.center(), Modifiers::none());
draw(cx);
assert_eq!(read(&view, cx, |app| app.power_menu), Some(1));
// The pointer takes the highlight, and the check stays on what is saved.
let miser = cx.debug_bounds(Power::Miser.key()).expect("row");
cx.simulate_mouse_move(miser.center(), None, Modifiers::none());
draw(cx);
assert_eq!(read(&view, cx, |app| app.power_menu), Some(0));
let balanced = cx.debug_bounds(Power::Balanced.key()).expect("row");
let check = cx.debug_bounds("power-check").expect("check");
assert!(balanced.contains(&check.center()), "check on {check:?}");
// A disabled row ignores the click and leaves the menu to be dismissed.
let drain = cx.debug_bounds(Power::DrainMyBattery.key()).expect("row");
cx.simulate_click(drain.center(), Modifiers::none());
draw(cx);
read(&view, cx, |app| {
assert_eq!(app.power_choice, Some(Power::Balanced));
assert!(app.notice.is_none());
});
// The arrows step over what is not offered, and Enter chooses.
update(&view, cx, |app, cx| {
app.power_menu = None;
app.toggle_power_menu(cx);
});
press(cx, "down");
assert_eq!(read(&view, cx, |app| app.power_menu), Some(1));
press(cx, "up");
assert_eq!(read(&view, cx, |app| app.power_menu), Some(0));
press(cx, "enter");
read(&view, cx, |app| {
assert_eq!(app.power_choice, Some(Power::Miser));
assert_eq!(app.options.threads.max_threads, 2);
assert!(app.power_menu.is_none());
});
// The button closes what it opened, rather than the press outside the
// menu closing it only for the click to open it again.
draw(cx);
let toggle = cx.debug_bounds("power-efficiency").expect("control");
cx.simulate_mouse_move(toggle.center(), None, Modifiers::none());
cx.simulate_click(toggle.center(), Modifiers::none());
draw(cx);
assert!(read(&view, cx, |app| app.power_menu.is_some()));
cx.simulate_click(toggle.center(), Modifiers::none());
draw(cx);
assert!(read(&view, cx, |app| app.power_menu.is_none()));
}
+6
View File
@@ -72,6 +72,12 @@ pub mod size {
/// A crumb's sibling menu.
pub const SIBLING_MENU: Rems = Rems(24.0);
pub const SIBLING_MENU_HEIGHT: Rems = Rems(32.0);
/// The Power Efficiency menu: narrower than a sibling menu, since its
/// names are four known words, but wide enough for Drain My Battery
/// beside the check, bar and count.
pub const POWER_MENU: Rems = Rems(22.0);
/// One bar of the Power Efficiency gauge.
pub const SIGNAL_BAR: Rems = Rems(0.1875);
/// A list row's share bar.
pub const ROW_BAR: Rems = Rems(5.5);
/// A legend or identity swatch.
+203
View File
@@ -476,10 +476,13 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div {
} else {
0..0
};
// Short of room, the trail gives up its start, never the crumb you are
// in and its menu: content packed to the end overflows to the left.
let mut row = div()
.flex()
.flex_row()
.items_center()
.justify_end()
.gap(space::XXS)
.min_w_0()
.overflow_hidden();
@@ -978,6 +981,206 @@ fn view_settings(
.child(hidden)
.child(apparent)
.child(depth_control)
.child(power_efficiency(app, cx))
}
/// What the tooltip says the choice will do, where the gauge alone cannot.
/// Measured on an 18-core Apple silicon Mac scanning its whole Data volume
/// (medians of three): 4 workers 209 s and 433 CPU-seconds, 8 workers 133 s
/// and 580, 18 workers 137 s and 1,314. Elsewhere the shape is expected, not
/// measured, so it gives no numbers.
const POWER_TRADEOFF: &str = if cfg!(target_os = "macos") {
"Up to about 8 workers a scan finishes sooner: a whole drive took a \
third less time with 8 than with Balanced. Past that it is no faster, \
but uses over twice the CPU and runs the fans at full speed."
} else {
"More workers finish a scan sooner only up to a point. Past it they \
use more CPU for no gain, and can run the fans at full speed."
};
/// How hard a scan may work, as a signal gauge framed like Depth; the
/// presets are in a menu built like the sibling menu, so the control costs
/// the bar no more than one button. Like the other settings, focus returns
/// to the treemap.
fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div {
use crate::power::{self, PowerEfficiency};
let theme = cx.omarchy().clone();
let cpus = app.cpu_threads;
let threads = app.options.threads.max_threads.min(cpus);
let name = app.power_choice.map_or("Custom", PowerEfficiency::name);
let open = app.power_menu.is_some();
let trigger = div()
.id("power-efficiency")
.debug_selector(|| "power-efficiency".into())
.flex()
.flex_row()
.items_center()
.border_1()
.border_color(theme.control_border())
.on_hover(cx.listener(|this, hovered: &bool, _, cx| {
this.power_hover = *hovered;
cx.notify();
}))
.child(
button("power-toggle", "", ButtonVariant::Secondary, cx)
.accessibility_label(format!("Power Efficiency: {name}"))
.selected(open)
.tab_stop(false)
.child(widgets::signal(
PowerEfficiency::signal(threads, cpus),
cx,
))
.child(
div()
.text_size(text::CAPTION)
.text_color(theme.secondary)
.child("\u{25be}"),
)
.on_click(cx.listener(|this, _, window, cx| {
this.toggle_power_menu(cx);
window.focus(&this.focus, cx);
})),
);
// An open menu says it all; the tooltip would only cover it.
let trigger = if open {
trigger
} else {
with_tooltip(
trigger,
format!(
"Power Efficiency: {name} \u{00b7} {} of {cpus} CPUs\n\
{POWER_TRADEOFF}\nUsed from the next scan, and remembered.",
power::workers(threads)
),
)
};
let mut control = div().relative().child(trigger);
let Some(highlighted) = app.power_menu else {
return control;
};
let mut menu = div()
.id("power-menu")
.debug_selector(|| "power-menu".into())
.occlude()
.flex()
.flex_col()
.w(size::POWER_MENU)
.p(space::XS)
.bg(theme.surface)
.border_1()
.border_color(theme.control_border())
.shadow_lg()
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
if !this.power_hover {
this.power_menu = None;
cx.notify();
}
}))
.child(
div()
.flex()
.flex_row()
.justify_between()
.px(space::SM)
.py(space::XS)
.text_size(text::CAPTION)
.text_color(theme.secondary.opacity(0.8))
.child("Scan workers")
.child(format!("{cpus} CPUs")),
);
for (index, preset) in PowerEfficiency::ALL.into_iter().enumerate() {
let offered = preset.available(cpus);
let current = app.power_choice == Some(preset);
let count = preset.threads(cpus);
let row = div()
.id(preset.key())
.debug_selector(move || preset.key().into())
.flex()
.flex_row()
.items_center()
.gap(space::MD)
.px(space::SM)
.py(space::XS)
.when(index == highlighted && offered, |this| {
this.bg(theme.hover_fill())
})
// The saved preset keeps its check wherever the highlight goes;
// bold alone read as losing to the fill under the pointer.
.child(div().flex_shrink_0().w(icon::SM).when(current, |this| {
this.debug_selector(|| "power-check".into()).child(
gpui_omarchy::icon(gpui_omarchy::IconName::Check)
.size(icon::SM)
.text_color(theme.accent),
)
}))
.child(
div()
.flex_1()
.min_w_0()
.text_size(text::BODY)
.text_color(theme.bright)
.when(current, |this| this.font_weight(FontWeight::BOLD))
.whitespace_nowrap()
.overflow_hidden()
.text_ellipsis()
.child(preset.name()),
)
.child(div().flex_shrink_0().w(size::ROW_BAR).child(widgets::bar(
count as f32 / cpus as f32,
theme.accent,
cx,
)))
.child(
div()
.flex_shrink_0()
.w(size::SIZE_LANE)
.flex()
.justify_end()
.text_size(text::BODY)
.text_color(theme.secondary)
.child(power::workers(count)),
);
// A preset this machine cannot tell apart from the one below it is
// shown, so the scale stays the same everywhere, but not offered.
let row = if offered {
// The pointer moves the one highlight the arrows move, so two
// filled rows never compete with the check.
row.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
if *hovered && this.power_menu.is_some() {
this.power_menu = Some(index);
cx.notify();
}
}))
.on_click(cx.listener(move |this, _, window, cx| {
this.set_power_efficiency(preset, cx);
window.focus(&this.focus, cx);
}))
} else {
let below = PowerEfficiency::ALL[index - 1].name();
with_tooltip(
row.opacity(0.45),
format!("Same as {below} with {cpus} CPUs"),
)
};
menu = menu.child(row);
}
control = control.child(
div().absolute().top_full().right_0().child(
deferred(
// Hung from the gauge's right edge: the bar's last control,
// so the menu opens inward rather than off the window.
anchored()
.anchor(gpui_kit::Anchor::TopRight)
.snap_to_window_with_margin(px(8.))
.offset(gpui_kit::point(px(0.), px(4.)))
.child(menu),
)
.with_priority(2),
),
);
control
}
// ── trail and legend ────────────────────────────────────────────────────
+31
View File
@@ -423,6 +423,37 @@ pub fn bar(fraction: f32, color: Hsla, cx: &App) -> Div {
)
}
/// Four rising bars with `filled` of them lit, as a signal meter reads:
/// how hard a scan is allowed to work, without a word in the bar.
pub fn signal(filled: usize, cx: &App) -> Div {
let theme = cx.omarchy();
let mut bars = div()
.flex()
.flex_row()
.items_end()
.gap(space::XXS)
.h(crate::ui::icon::SM);
for step in 1..=SIGNAL_STEPS {
// Heights step by quarters of the icon slot, so the tallest bar is
// the height of the text beside it.
let height = crate::ui::icon::SM.0 * step as f32 / SIGNAL_STEPS as f32;
bars = bars.child(
div()
.w(crate::ui::size::SIGNAL_BAR)
.h(gpui_kit::Rems(height))
.bg(if step <= filled {
theme.bright
} else {
theme.control_border()
}),
);
}
bars
}
/// One bar per Power Efficiency preset.
const SIGNAL_STEPS: usize = crate::power::PowerEfficiency::ALL.len();
/// A square of colour, for a legend or an identity.
pub fn swatch(color: Hsla) -> Div {
div()
+4
View File
@@ -38,3 +38,7 @@ trash = { version = "5.2.9", default-features = false }
[dev-dependencies]
tempfile = "3"
# CPU-only sampling; the GUI dependency graph already pins this version.
[target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies]
sysinfo = { version = "0.31.4", default-features = false, features = ["system"] }
@@ -0,0 +1,60 @@
//! One scan of `ROOT` with a fixed pool of `WORKERS`, the way a Power
//! Efficiency preset runs it, reported as one JSON line. Driven by
//! `scripts/bench-scan-workers.py`, which times it and samples the machine.
//!
//! ```sh
//! cargo run --release -p disktree-core --example scan_workers -- ROOT WORKERS
//! ```
use std::path::PathBuf;
use std::time::{Duration, Instant};
use disktree_core::scan::{ScanHandle, ScanOptions};
use disktree_core::scan_threads::ScanThreads;
fn main() {
let mut args = std::env::args_os().skip(1);
let (Some(root), Some(workers)) = (args.next(), args.next()) else {
eprintln!("usage: scan_workers ROOT WORKERS");
std::process::exit(2);
};
let Some(workers) = workers
.to_str()
.and_then(|value| value.parse::<usize>().ok())
.filter(|&value| value > 0)
else {
eprintln!("WORKERS must be a positive integer");
std::process::exit(2);
};
let options = ScanOptions {
// What `PowerEfficiency::policy` sets: a fixed pool, no governor.
threads: ScanThreads {
max_threads: workers,
adaptive: false,
system_cpu_limit: None,
..ScanThreads::default()
},
..ScanOptions::default()
};
let start = Instant::now();
let handle = ScanHandle::spawn(PathBuf::from(root), options);
let node = loop {
if let Some(result) = handle.poll() {
match result {
Ok(node) => break node,
Err(error) => {
eprintln!("scan failed: {error}");
std::process::exit(1);
}
}
}
std::thread::sleep(Duration::from_millis(20));
};
let elapsed = start.elapsed().as_secs_f64();
let progress = handle.progress.snapshot();
println!(
"{{\"workers\":{workers},\"pool\":{},\"elapsed\":{elapsed},\
\"files\":{},\"dirs\":{},\"bytes\":{},\"errors\":{}}}",
progress.threads, node.files, node.dirs, node.bytes, progress.errors
);
}
+1
View File
@@ -14,6 +14,7 @@ pub mod insights;
mod mft;
pub mod removal;
pub mod scan;
pub mod scan_threads;
pub mod size;
pub mod space;
pub mod tree;
+229 -8
View File
@@ -28,6 +28,7 @@ use std::thread;
use rayon::Scope;
use rustc_hash::FxHashSet;
use crate::scan_threads::{Admission, ControllerGuard, ScanThreads};
use crate::tree::{Metric, Node, NodeKind, Seen, aggregate, aggregate_deduped};
/// Errors kept verbatim before the list is truncated; the count keeps rising.
@@ -59,6 +60,8 @@ pub struct ScanOptions {
pub dedup_hardlinks: bool,
/// Whether children are ranked by bytes or by file count.
pub metric: Metric,
/// Directory admission for this scan; other scans have their own budget.
pub threads: ScanThreads,
}
impl Default for ScanOptions {
@@ -71,6 +74,7 @@ impl Default for ScanOptions {
max_depth: None,
dedup_hardlinks: true,
metric: Metric::Bytes,
threads: ScanThreads::default(),
}
}
}
@@ -89,6 +93,11 @@ pub struct ScanProgress {
finished: AtomicBool,
cancelled: AtomicBool,
messages: Mutex<Vec<String>>,
pub(crate) threads: AtomicUsize,
pub(crate) threads_settled: AtomicBool,
pub(crate) thread_tuning_complete: AtomicBool,
pub(crate) system_cpu_limited: AtomicBool,
pub(crate) worker_transitions: AtomicU64,
}
/// A point-in-time view of [`ScanProgress`].
@@ -100,11 +109,21 @@ pub struct ScanSnapshot {
pub errors: u64,
pub finished: bool,
pub cancelled: bool,
/// Admitted directory jobs, not a machine-wide thread limit.
pub threads: usize,
pub threads_settled: bool,
pub thread_tuning_complete: bool,
pub system_cpu_limited: bool,
pub worker_transitions: u64,
/// Up to [`MAX_ERROR_DETAIL`] unreadable paths, most recent last.
pub messages: Vec<String>,
}
impl ScanProgress {
pub(crate) fn entries(&self) -> u64 {
self.files.load(Ordering::Relaxed) + self.dirs.load(Ordering::Relaxed)
}
/// What a directory's listing found (see `Tally`), or what a reader
/// that measures in bulk has come across so far.
pub(crate) fn add(&self, files: u64, dirs: u64, bytes: u64) {
@@ -155,6 +174,13 @@ impl ScanProgress {
errors: self.errors.load(Ordering::Relaxed),
finished: self.finished.load(Ordering::Relaxed),
cancelled: self.is_cancelled(),
threads: self.threads.load(Ordering::Relaxed),
threads_settled: self.threads_settled.load(Ordering::Relaxed),
thread_tuning_complete: self
.thread_tuning_complete
.load(Ordering::Relaxed),
system_cpu_limited: self.system_cpu_limited.load(Ordering::Relaxed),
worker_transitions: self.worker_transitions.load(Ordering::Relaxed),
messages: lock(&self.messages).clone(),
}
}
@@ -743,6 +769,32 @@ impl PendingDir {
}
fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
let owned = fixed_pool(context.options.threads)?;
let pool = owned.as_ref().unwrap_or_else(|| &WALK_POOL);
scan_on_pool(root, context, pool)
}
/// Explicit fixed budgets cover enumeration, the Windows file-table path and
/// tree finishing. A scan owns its pool so a new setting needs no global reset.
/// Default core callers and experimental adaptive scans retain the shared pool.
fn fixed_pool(threads: ScanThreads) -> io::Result<Option<rayon::ThreadPool>> {
if threads.adaptive || threads.max_threads == usize::MAX {
return Ok(None);
}
let cpus = thread::available_parallelism().map_or(1, usize::from);
rayon::ThreadPoolBuilder::new()
.num_threads(threads.max_threads.clamp(1, cpus))
.thread_name(|index| format!("disktree-scan-{index}"))
.build()
.map(Some)
.map_err(io::Error::other)
}
fn scan_on_pool(
root: &Path,
context: &Arc<WalkContext>,
pool: &rayon::ThreadPool,
) -> io::Result<Node> {
let root_meta = fs::metadata(root)?;
if !root_meta.is_dir() {
return Err(io::Error::new(
@@ -774,7 +826,7 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
#[cfg(windows)]
{
let progress = &context.progress;
let read = WALK_POOL.install(|| {
let read = pool.install(|| {
crate::mft::scan(root, canonical, &context.options, progress)
});
if let Some(node) = read {
@@ -784,7 +836,7 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
if progress.is_cancelled() {
return Err(crate::mft::cancelled());
}
let node = finish_tree(node, &context.options);
let node = finish_tree(node, &context.options, pool);
// The reader counted every file on the volume; the tree may
// hold fewer.
progress.settle(node.files, node.dirs, node.bytes);
@@ -816,13 +868,52 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
0,
));
let context: &WalkContext = context;
WALK_POOL.install(|| rayon::scope(|scope| walk(scope, &root_dir, context)));
pool.install(|| {
let mut threads = context.options.threads.normalized();
threads.max_threads =
threads.max_threads.min(rayon::current_num_threads());
context
.progress
.threads
.store(threads.max_threads, Ordering::Relaxed);
context
.progress
.threads_settled
.store(true, Ordering::Relaxed);
context
.progress
.thread_tuning_complete
.store(!threads.adaptive, Ordering::Relaxed);
if !threads.adaptive
&& threads.max_threads == rayon::current_num_threads()
{
// Pool-sized fixed scans need no admission lock or ready queue. Keep
// existing core callers on Rayon's direct scheduling path.
rayon::scope(|scope| {
dispatch_fixed(scope, &root_dir, context);
});
} else {
let admission =
Arc::new(Admission::new(root_dir, threads.max_threads));
// The controller owns no Rayon worker and is joined before finishing
// the tree, where entry throughput no longer describes useful work.
let _controller = ControllerGuard::spawn(
threads,
Arc::clone(&admission),
Arc::clone(&context.progress),
)?;
rayon::scope(|scope| {
dispatch(scope, admission.start(), context, &admission);
});
}
Ok::<(), io::Error>(())
})?;
let node = lock(&context.root).take();
let node = node.ok_or_else(|| {
io::Error::other(format!("{} produced no tree", root.display()))
})?;
Ok(finish_tree(node, &context.options))
Ok(finish_tree(node, &context.options, pool))
}
/// The walk's workers, and the file table reader's. Listing directories
@@ -883,11 +974,50 @@ impl Tally {
/// Read one directory, spawn a task per subdirectory, then report completion.
///
/// Flat tasks inside the scope: the worker stack never grows with tree depth.
fn walk<'scope>(
fn dispatch_fixed<'scope>(
scope: &Scope<'scope>,
dir: &Arc<PendingDir>,
context: &'scope WalkContext,
) {
for child in walk(dir, context) {
scope.spawn(move |scope| {
dispatch_fixed(scope, &child, context);
});
}
}
/// Read one directory, spawn a task per subdirectory, then report completion.
///
/// Flat tasks inside the scope: the worker stack never grows with tree depth.
fn dispatch<'scope>(
scope: &Scope<'scope>,
jobs: Vec<Arc<PendingDir>>,
context: &'scope WalkContext,
admission: &Arc<Admission<Arc<PendingDir>>>,
) {
for dir in jobs {
let admission = Arc::clone(admission);
scope.spawn(move |scope| {
let mut next = Some(dir);
while let Some(dir) = next.take() {
let children = walk(&dir, context);
let mut jobs = admission.complete(children);
// Continue locally into one ready descendant; only surplus
// jobs are offered to other workers. A running directory is
// never split, and a retirement returns from this loop.
next = jobs.pop();
dispatch(scope, jobs, context, &admission);
}
});
}
}
fn walk(dir: &Arc<PendingDir>, context: &WalkContext) -> Vec<Arc<PendingDir>> {
if context.cancelled() {
// Queued jobs still own a pending token even when no I/O is needed.
signal_done(dir, context);
return Vec::new();
}
let mut subdirs: Vec<Arc<PendingDir>> = Vec::new();
let mut leaves: Vec<Node> = Vec::new();
let mut tally = Tally::default();
@@ -952,17 +1082,19 @@ fn walk<'scope>(
partial.children.reserve_exact(leaves.len() + spawned);
partial.children.extend(leaves);
}
let mut children = Vec::new();
if descend {
for subdir in subdirs {
if context.cancelled() {
break;
}
dir.pending.fetch_add(1, Ordering::AcqRel);
scope.spawn(move |scope| walk(scope, &subdir, context));
children.push(subdir);
}
}
signal_done(dir, context);
children
}
/// Report that one task for `dir` is done: either its own scan, or one of its
@@ -987,8 +1119,12 @@ fn signal_done(dir: &Arc<PendingDir>, context: &WalkContext) {
/// Charge a hardlinked file once, derive every aggregate from the result,
/// then classify. On the walk's pool: the UI's own work on the global pool
/// must not queue behind a scan finishing.
fn finish_tree(mut node: Node, options: &ScanOptions) -> Node {
WALK_POOL.install(|| {
fn finish_tree(
mut node: Node,
options: &ScanOptions,
pool: &rayon::ThreadPool,
) -> Node {
pool.install(|| {
if options.dedup_hardlinks {
aggregate_deduped(&mut node, options.metric, &Seen::new());
} else {
@@ -1195,6 +1331,91 @@ mod tests {
})
}
#[test]
fn fixed_worker_pools_change_size_without_reinitializing_rayon() {
let cpus = thread::available_parallelism().map_or(1, usize::from);
// Two live pools have independent limits; constructing the first must
// not freeze the choice for a later scan or the global UI pool.
let make = |count| {
fixed_pool(ScanThreads {
max_threads: count,
..ScanThreads::default()
})
.expect("pool")
.expect("explicit fixed pool")
};
let small = make(1);
let large = make(4);
assert_eq!(small.install(rayon::current_num_threads), 1);
assert_eq!(large.install(rayon::current_num_threads), 4.min(cpus));
assert!(
fixed_pool(ScanThreads::default())
.expect("default")
.is_none()
);
assert!(
fixed_pool(ScanThreads {
adaptive: true,
max_threads: 4,
..ScanThreads::default()
})
.expect("adaptive")
.is_none()
);
}
#[test]
fn fixed_worker_pools_preserve_a_wide_deep_tree() {
let temp = TempDir::new().expect("tempdir");
for index in 0..96 {
write(temp.path(), &format!("d{index}/nested/file"), index + 1);
}
for threads in [1, 2, 4, 8, usize::MAX] {
let mut settings = options();
settings.threads.max_threads = threads;
let tree = scan_dir(temp.path(), &settings);
assert_eq!(tree.files, 96);
assert_eq!(tree.dirs, 193);
assert_eq!(tree.bytes, (1..=96).sum::<u64>());
}
}
#[test]
fn cancelled_queued_jobs_release_parent_completion_tokens() {
let temp = TempDir::new().expect("tempdir");
for index in 0..128 {
write(temp.path(), &format!("d{index}/file"), 1);
}
let progress = Arc::new(ScanProgress::default());
let context = Arc::new(WalkContext {
known: None,
options: options(),
progress: Arc::clone(&progress),
root_device: Mutex::new(None),
foreign_mounts: OnceLock::new(),
never_scanned: OnceLock::new(),
visited_dirs: Mutex::new(FxHashSet::default()),
root: Mutex::new(None),
volume: OnceLock::new(),
});
let root = Arc::new(PendingDir::new(
temp.path().to_path_buf(),
file_name(temp.path()),
None,
0,
));
let queued = walk(&root, &context);
assert_eq!(queued.len(), 128);
assert!(lock(&context.root).is_none());
progress.cancel();
for dir in queued {
assert!(walk(&dir, &context).is_empty());
}
let tree = lock(&context.root).take().expect("root completed");
assert_eq!(tree.children.len(), 128);
assert!(tree.children.iter().all(|child| child.children.is_empty()));
}
#[test]
fn totals_are_summed_bottom_up() {
let temp = TempDir::new().expect("tempdir");
+733
View File
@@ -0,0 +1,733 @@
//! Scan-local admission: queued directories never occupy Rayon workers.
use std::sync::{Mutex, MutexGuard, PoisonError};
/// Filesystem concurrency for one scan, independent of the global Rayon pool.
/// A scan crossing several volumes shares this budget; separate scans do not.
#[derive(Clone, Copy, Debug)]
pub struct ScanThreads {
/// Fixed scan workers, capped by available CPUs; `usize::MAX` uses the
/// shared platform-default pool. With `adaptive`, maximum admitted directory
/// jobs instead, including jobs awaiting a Rayon worker.
pub max_threads: usize,
/// Search below the cap and respond to whole-system CPU pressure.
pub adaptive: bool,
/// Fraction of initial entries/second a candidate must retain.
pub retained_throughput: f64,
/// Best-effort whole-system CPU ceiling; `None` disables the governor.
pub system_cpu_limit: Option<f64>,
}
impl Default for ScanThreads {
fn default() -> Self {
Self {
// Preserve core callers' pool-sized fixed concurrency. The app
// supplies the user's Power Efficiency preset before scanning.
max_threads: usize::MAX,
// Adaptive admission remains an explicit experimental opt-in.
adaptive: false,
retained_throughput: 0.80,
system_cpu_limit: Some(0.80),
}
}
}
impl ScanThreads {
pub(crate) fn normalized(self) -> Self {
Self {
max_threads: self.max_threads.max(1),
retained_throughput: if (0.0..=1.0)
.contains(&self.retained_throughput)
{
self.retained_throughput
} else {
0.80
},
system_cpu_limit: self.system_cpu_limit.filter(|limit| {
limit.is_finite() && *limit > 0.0 && *limit <= 1.0
}),
..self
}
}
}
pub(crate) struct Admission<T> {
state: Mutex<Queue<T>>,
}
struct Queue<T> {
pending: Vec<T>,
active: usize,
limit: usize,
epoch: u64,
starved: bool,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Sample {
pub(crate) active: usize,
pub(crate) limit: usize,
pub(crate) epoch: u64,
pub(crate) starved: bool,
}
impl Sample {
pub(crate) const fn settled(self) -> bool {
self.active <= self.limit
}
}
impl<T> Admission<T> {
pub(crate) fn new(root: T, limit: usize) -> Self {
Self {
state: Mutex::new(Queue {
pending: vec![root],
active: 0,
limit: limit.max(1),
epoch: 0,
starved: false,
}),
}
}
fn lock(&self) -> MutexGuard<'_, Queue<T>> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn start(&self) -> Vec<T> {
Self::admit(&mut self.lock())
}
/// Each submitted job hands back its slot exactly once, after its own
/// parent-completion signal. Its children already hold pending tokens.
pub(crate) fn complete(&self, children: Vec<T>) -> Vec<T> {
let mut state = self.lock();
state.active -= 1;
state.pending.extend(children);
let jobs = Self::admit(&mut state);
drop(state);
jobs
}
fn admit(state: &mut Queue<T>) -> Vec<T> {
let count = state
.limit
.saturating_sub(state.active)
.min(state.pending.len());
let split = state.pending.len() - count;
let jobs = state.pending.split_off(split);
state.active += jobs.len();
state.starved |= state.active < state.limit;
jobs
}
/// The same lock guards dispatch and changes, so a settled snapshot
/// cannot precede a late dispatch made using the old limit.
pub(crate) fn set_limit(&self, limit: usize) {
let mut state = self.lock();
let limit = limit.max(1);
if state.limit != limit {
state.limit = limit;
state.epoch += 1;
}
}
pub(crate) fn sample(&self) -> Sample {
let mut state = self.lock();
Sample {
active: state.active,
limit: state.limit,
epoch: state.epoch,
// A long directory can remain undersupplied for many samples.
// Clearing the history must not erase the current condition,
// including an increase awaiting the next dispatch boundary.
starved: std::mem::take(&mut state.starved)
|| state.active < state.limit,
}
}
}
/// One reference, then a bounded accepted/rejected bracket. This targets a
/// sampled rate, not a guarantee about an evolving tree's completion time.
pub(crate) struct Search {
reference: Option<f64>,
accepted: usize,
rejected: usize,
candidate: usize,
passes: u8,
failures: u8,
windows: u8,
retained: f64,
pub(crate) done: bool,
}
impl Search {
pub(crate) const fn new(initial: usize, retained: f64) -> Self {
Self {
reference: None,
accepted: initial,
rejected: 0,
candidate: initial,
passes: 0,
failures: 0,
windows: 0,
retained,
done: initial <= 1,
}
}
pub(crate) fn sample(&mut self, rate: Option<f64>) -> usize {
if self.done {
return self.accepted;
}
let Some(reference) = self.reference else {
if let Some(rate) = rate.filter(|rate| *rate > 0.0) {
self.reference = Some(rate);
self.candidate = (self.accepted / 2).max(1);
self.windows = 0;
} else {
self.windows += 1;
self.done = self.windows == 3;
}
return self.candidate;
};
self.windows += 1;
if let Some(rate) = rate {
if rate >= reference * self.retained {
self.passes += 1;
} else {
self.failures += 1;
}
}
if self.passes == 2 || self.failures == 2 || self.windows == 3 {
if self.passes == 2 {
self.accepted = self.candidate;
} else {
self.rejected = self.candidate;
}
self.done = self.accepted - self.rejected <= 1;
self.candidate = if self.done {
self.accepted
} else {
self.rejected + (self.accepted - self.rejected) / 2
};
self.passes = 0;
self.failures = 0;
self.windows = 0;
}
self.candidate
}
}
pub(crate) struct Governor {
ceiling: Option<f64>,
cap: usize,
high: u8,
low: u8,
pub(crate) pressured: bool,
}
impl Governor {
pub(crate) const fn new(cap: usize, ceiling: Option<f64>) -> Self {
Self {
ceiling,
cap,
high: 0,
low: 0,
pressured: false,
}
}
pub(crate) fn admitted(&self, desired: usize) -> usize {
if self.ceiling.is_none() {
desired
} else {
desired.min(self.cap)
}
}
pub(crate) fn sample(
&mut self,
usage: Option<f64>,
admitted: usize,
desired: usize,
settled: bool,
) -> usize {
let Some(ceiling) = self.ceiling else {
return desired;
};
if let Some(usage) = usage {
self.pressured = usage > ceiling;
if self.pressured {
self.low = 0;
self.high = self.high.saturating_add(1).min(2);
if self.high >= 2 && settled {
self.cap = (admitted / 2).max(1);
self.high = 0;
}
} else if usage < (ceiling - 0.05).max(0.0) {
self.high = 0;
self.low = self.low.saturating_add(1).min(4);
if self.low >= 4 && settled {
self.cap = (self.cap + 1).min(desired.max(self.cap));
self.low = 0;
}
} else {
self.high = 0;
self.low = 0;
}
} else {
// Missing measurements cannot establish spare capacity.
self.high = 0;
self.low = 0;
}
desired.min(self.cap)
}
}
use std::io;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Condvar};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::scan::ScanProgress;
pub(crate) struct ControllerGuard {
stop: Arc<(Mutex<bool>, Condvar)>,
worker: Option<JoinHandle<()>>,
}
impl ControllerGuard {
pub(crate) fn spawn<T: Send + 'static>(
options: ScanThreads,
admission: Arc<Admission<T>>,
progress: Arc<ScanProgress>,
) -> io::Result<Option<Self>> {
if !options.adaptive {
return Ok(None);
}
let stop = Arc::new((Mutex::new(false), Condvar::new()));
let wake = Arc::clone(&stop);
let worker = thread::Builder::new()
.name("disktree-admission".into())
.spawn(move || {
control(options, &admission, &progress, &wake);
})?;
Ok(Some(Self {
stop,
worker: Some(worker),
}))
}
}
impl Drop for ControllerGuard {
fn drop(&mut self) {
*self.stop.0.lock().unwrap_or_else(PoisonError::into_inner) = true;
self.stop.1.notify_one();
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
fn control<T>(
options: ScanThreads,
admission: &Admission<T>,
progress: &ScanProgress,
stop: &(Mutex<bool>, Condvar),
) {
let mut cpu = options.system_cpu_limit.map(|_| CpuSampler::new());
control_with(
options,
admission,
progress,
stop,
Duration::from_millis(250),
|| cpu.as_mut().and_then(CpuSampler::sample),
);
}
fn control_with<T>(
options: ScanThreads,
admission: &Admission<T>,
progress: &ScanProgress,
stop: &(Mutex<bool>, Condvar),
interval: Duration,
mut sample_cpu: impl FnMut() -> Option<f64>,
) {
// Two 250 ms votes distinguish a candidate from a transient burst. CPU
// counters are sampled less often because they have coarser resolution.
let mut search =
Search::new(options.max_threads, options.retained_throughput);
let mut governor =
Governor::new(options.max_threads, options.system_cpu_limit);
let mut desired = options.max_threads;
let mut cpu_at = Instant::now();
let mut start = Instant::now();
let mut entries = progress.entries();
let mut epoch = 0;
let mut measuring = false;
loop {
let (stopped, _) = stop
.1
.wait_timeout_while(
stop.0.lock().unwrap_or_else(PoisonError::into_inner),
interval,
|stopped| !*stopped,
)
.unwrap_or_else(PoisonError::into_inner);
if *stopped || progress.is_cancelled() {
return;
}
drop(stopped);
let sample = admission.sample();
let mut limit = sample.limit;
if cpu_at.elapsed() >= interval * 2 {
limit = governor.sample(
sample_cpu(),
sample.limit,
desired,
sample.settled(),
);
cpu_at = Instant::now();
}
let limited = governor.pressured || limit < desired;
progress
.system_cpu_limited
.store(limited, Ordering::Relaxed);
progress
.threads_settled
.store(sample.settled(), Ordering::Relaxed);
let current = progress.entries();
let now = Instant::now();
if limited || !sample.settled() || epoch != sample.epoch || !measuring {
measuring = !limited && sample.settled();
} else if !search.done {
let rate = (!sample.starved && current > entries).then(|| {
(current - entries) as f64
/ now.duration_since(start).as_secs_f64()
});
desired = search.sample(rate);
limit = governor.admitted(desired);
}
if limit != sample.limit {
admission.set_limit(limit);
progress.threads.store(limit, Ordering::Relaxed);
progress.worker_transitions.fetch_add(1, Ordering::Relaxed);
progress.threads_settled.store(false, Ordering::Relaxed);
measuring = false;
}
progress
.thread_tuning_complete
.store(search.done, Ordering::Relaxed);
entries = current;
start = now;
epoch = sample.epoch;
}
}
struct CpuSampler {
#[cfg(any(target_os = "macos", target_os = "linux"))]
system: sysinfo::System,
}
#[cfg_attr(
not(any(target_os = "macos", target_os = "linux")),
allow(
clippy::missing_const_for_fn,
clippy::unused_self,
reason = "The fallback mirrors the stateful, non-const native API."
)
)]
impl CpuSampler {
fn new() -> Self {
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
let mut system = sysinfo::System::new();
system.refresh_cpu_usage();
Self { system }
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
Self {}
}
fn sample(&mut self) -> Option<f64> {
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
self.system.refresh_cpu_usage();
let usage = f64::from(self.system.global_cpu_usage()) / 100.0;
// sysinfo reports zero on some native read failures. Conservatively
// ignore zero too: it must not be evidence for restoring workers.
(!self.system.cpus().is_empty() && usage > 0.0 && usage <= 1.0)
.then_some(usage)
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
#[test]
fn search_refines_one_reference_without_compounding_loss() {
let mut search = Search::new(8, 0.8);
assert_eq!(search.sample(Some(100.0)), 4);
assert_eq!(search.sample(Some(85.0)), 4);
assert_eq!(search.sample(Some(85.0)), 2);
assert_eq!(search.sample(Some(70.0)), 2);
assert_eq!(search.sample(Some(70.0)), 3);
assert_eq!(search.sample(Some(81.0)), 3);
assert_eq!(search.sample(Some(81.0)), 3);
assert!(search.done);
}
#[test]
fn long_directory_never_becomes_a_fully_supplied_window() {
let admission = Admission::new(0, 8);
assert_eq!(admission.start(), vec![0]);
let mut search = Search::new(8, 0.8);
for _ in 0..6 {
let sample = admission.sample();
assert!(sample.settled());
assert!(sample.starved);
assert_eq!(search.sample((!sample.starved).then_some(100.0)), 8);
}
assert!(search.reference.is_none());
assert!(search.done);
}
#[test]
fn increased_limit_is_not_supplied_until_jobs_are_dispatched() {
let admission = Admission::new(0, 1);
assert_eq!(admission.start(), vec![0]);
assert_eq!(admission.complete((1..=8).collect()).len(), 1);
admission.set_limit(8);
let mut search = Search::new(16, 0.8);
assert_eq!(search.sample(Some(100.0)), 8);
for _ in 0..3 {
let sample = admission.sample();
assert!(sample.settled());
assert!(sample.starved);
search.sample((!sample.starved).then_some(100.0));
}
// Even an apparently fast candidate cannot be accepted while only
// one job is admitted and the other ready jobs remain queued.
assert_eq!(search.accepted, 16);
assert_eq!(search.rejected, 8);
assert_eq!(admission.complete(vec![9]).len(), 8);
assert!(!admission.sample().starved);
}
#[test]
fn inconclusive_windows_cannot_accept_a_reduction() {
let mut search = Search::new(4, 0.8);
assert_eq!(search.sample(Some(100.0)), 2);
for _ in 0..2 {
assert_eq!(search.sample(None), 2);
}
assert_eq!(search.sample(None), 3);
assert_eq!(search.sample(Some(90.0)), 3);
assert_eq!(search.sample(None), 3);
assert_eq!(search.sample(None), 4);
assert!(search.done);
}
#[test]
fn governor_waits_for_retirement_and_recovers_without_exceeding_target() {
let mut governor = Governor::new(8, Some(0.8));
assert_eq!(governor.sample(Some(0.9), 8, 8, true), 8);
assert_eq!(governor.sample(Some(0.9), 8, 8, true), 4);
for _ in 0..300 {
assert_eq!(governor.sample(Some(0.9), 4, 8, false), 4);
}
assert_eq!(governor.sample(Some(0.9), 4, 8, true), 2);
assert_eq!(governor.sample(None, 2, 8, true), 2);
for _ in 0..3 {
assert_eq!(governor.sample(Some(0.5), 2, 8, true), 2);
}
assert_eq!(governor.sample(Some(0.5), 2, 8, true), 3);
// A throughput decision does not manufacture a CPU-pressure cap.
let mut governor = Governor::new(8, Some(0.8));
for _ in 0..4 {
assert_eq!(governor.sample(Some(0.5), 2, 2, true), 2);
}
assert_eq!(governor.admitted(8), 8);
}
fn wait_until(mut ready: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(5);
while !ready() {
assert!(Instant::now() < deadline, "controller timed out");
thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn controller_retires_recovers_after_search_and_cancels() {
let admission = Arc::new(Admission::new(0, 4));
assert_eq!(admission.start(), vec![0]);
assert_eq!(admission.complete(vec![1, 2, 3, 4]).len(), 4);
let progress = Arc::new(ScanProgress::default());
// 0 is missing, 1 is below the ceiling, 2 is above it.
let cpu = Arc::new(std::sync::atomic::AtomicUsize::new(1));
let controller_admission = Arc::clone(&admission);
let controller_progress = Arc::clone(&progress);
let controller_cpu = Arc::clone(&cpu);
let controller = thread::spawn(move || {
control_with(
ScanThreads {
max_threads: 4,
adaptive: true,
..ScanThreads::default()
},
&controller_admission,
&controller_progress,
&(Mutex::new(false), Condvar::new()),
Duration::from_millis(2),
|| match controller_cpu.load(Ordering::Relaxed) {
1 => Some(0.5),
2 => Some(0.95),
_ => None,
},
);
});
// No entries gives an inconclusive bounded search. The governor must
// remain active after that search completes.
wait_until(|| progress.snapshot().thread_tuning_complete);
cpu.store(2, Ordering::Relaxed);
wait_until(|| admission.sample().limit == 2);
thread::sleep(Duration::from_millis(30));
assert_eq!(admission.sample().limit, 2);
assert!(!progress.snapshot().threads_settled);
assert!(admission.complete(Vec::new()).is_empty());
assert!(admission.complete(Vec::new()).is_empty());
wait_until(|| admission.sample().limit == 1);
cpu.store(0, Ordering::Relaxed);
assert!(admission.complete(Vec::new()).is_empty());
thread::sleep(Duration::from_millis(30));
assert_eq!(admission.sample().limit, 1);
cpu.store(1, Ordering::Relaxed);
wait_until(|| admission.sample().limit == 4);
assert!(progress.snapshot().worker_transitions >= 5);
progress.cancel();
controller.join().expect("cancelled controller");
assert!(admission.complete(Vec::new()).is_empty());
assert_eq!(admission.sample().active, 0);
}
fn execute(
scope: &rayon::Scope<'_>,
jobs: Vec<usize>,
admission: &Arc<Admission<usize>>,
releases: &Arc<Mutex<Vec<Option<mpsc::Receiver<()>>>>>,
started: &mpsc::Sender<usize>,
completed: &mpsc::Sender<usize>,
) {
for job in jobs {
let admission = Arc::clone(admission);
let releases = Arc::clone(releases);
let started = started.clone();
let completed = completed.clone();
scope.spawn(move |scope| {
let children = if job == 0 {
(1..=4).collect()
} else if job <= 4 {
started.send(job).expect("started");
let release = releases.lock().expect("releases")[job]
.take()
.expect("one receiver");
release
.recv_timeout(Duration::from_secs(5))
.expect("release");
vec![job + 4]
} else {
Vec::new()
};
let next = admission.complete(children);
completed.send(job).expect("completed");
execute(
scope, next, &admission, &releases, &started, &completed,
);
});
}
}
#[test]
fn real_pool_retires_at_job_boundaries_and_drains_queued_descendants() {
let admission = Arc::new(Admission::new(0, 4));
let (started, starts) = mpsc::channel();
let (completed, completions) = mpsc::channel();
let (done, finished) = mpsc::channel();
let mut senders = Vec::new();
let mut receivers = Vec::new();
for _ in 0..=4 {
let (send, receive) = mpsc::channel();
senders.push(send);
receivers.push(Some(receive));
}
let releases = Arc::new(Mutex::new(receivers));
let worker_admission = Arc::clone(&admission);
let worker = thread::spawn(move || {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(4)
.build()
.expect("pool");
pool.scope(|scope| {
execute(
scope,
worker_admission.start(),
&worker_admission,
&releases,
&started,
&completed,
);
});
done.send(()).expect("done");
});
assert_eq!(
completions
.recv_timeout(Duration::from_secs(5))
.expect("root"),
0
);
let mut running = Vec::new();
for _ in 0..4 {
running.push(
starts.recv_timeout(Duration::from_secs(5)).expect("start"),
);
}
admission.set_limit(1);
assert!(!admission.sample().settled());
for (index, &job) in running[..3].iter().enumerate() {
senders[job].send(()).expect("release");
assert_eq!(
completions
.recv_timeout(Duration::from_secs(5))
.expect("done"),
job
);
let sample = admission.sample();
assert_eq!(sample.active, 3 - index);
assert_eq!(sample.settled(), index == 2);
}
// The last admitted job is still running; its siblings' descendants
// must remain ready rather than occupying blocked Rayon workers.
assert_eq!(admission.lock().pending.len(), 3);
admission.set_limit(2);
senders[running[3]].send(()).expect("last release");
finished
.recv_timeout(Duration::from_secs(5))
.expect("scope drained");
worker.join().expect("worker");
let mut remaining: Vec<_> = completions.try_iter().collect();
remaining.sort_unstable();
let mut expected = vec![running[3], 5, 6, 7, 8];
expected.sort_unstable();
assert_eq!(remaining, expected);
assert_eq!(admission.sample().active, 0);
}
}
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Time whole scans at several fixed worker counts and print the PR table.
Each run is one `scan_workers` example process under `/usr/bin/time`, so CPU
time is the scan's own user + system seconds. Whole-machine busy time is
sampled every half second while it runs (macOS `host_statistics`, Linux
`/proc/stat`). Rounds rotate the order so drift in the machine or the cache
does not favour one count. The first scan is an untimed warm-up.
scripts/bench-scan-workers.py /System/Volumes/Data --workers 18 8 4 2
Hold the machine quiet: a VM, an indexer or a build skews every column.
"""
import argparse
import ctypes
import fcntl
import json
import os
import pathlib
import platform
import re
import statistics
import subprocess
import sys
import time
REPO = pathlib.Path(__file__).resolve().parent.parent
EXAMPLE = REPO / "target/release/examples/scan_workers"
def cpu_ticks():
"""(busy, total) ticks for the whole machine since boot."""
if platform.system() == "Darwin":
lib = ctypes.CDLL("/usr/lib/libSystem.B.dylib")
lib.mach_host_self.restype = ctypes.c_uint
ticks = (ctypes.c_uint * 4)()
count = ctypes.c_uint(4)
# HOST_CPU_LOAD_INFO: user, system, idle, nice.
if lib.host_statistics(lib.mach_host_self(), 3, ticks, ctypes.byref(count)):
raise OSError("host_statistics failed")
return sum(ticks) - ticks[2], sum(ticks)
fields = [int(x) for x in open("/proc/stat").readline().split()[1:]]
idle = fields[3] + fields[4]
return sum(fields) - idle, sum(fields)
def percent(value):
return "n/a" if value is None else f"{value:.0f}%"
def busy_percent(before, after):
busy, total = (a - b for a, b in zip(after, before))
return 100 * busy / total if total else None
def cpu_seconds(time_output):
"""User + system seconds from BSD or GNU `/usr/bin/time` output."""
user = re.search(r"([\d.]+) user|User time \(seconds\): ([\d.]+)", time_output)
system = re.search(r"([\d.]+) sys|System time \(seconds\): ([\d.]+)", time_output)
return sum(float(next(g for g in m.groups() if g)) for m in (user, system))
def scan(root, workers):
flag = "-l" if platform.system() == "Darwin" else "-v"
before = cpu_ticks()
started = time.monotonic()
process = subprocess.Popen(
["/usr/bin/time", flag, str(EXAMPLE), root, str(workers)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
# Its own group, so an interrupt never leaves a scan running.
start_new_session=True,
)
try:
out, err = process.communicate()
except BaseException:
os.killpg(process.pid, 9)
raise
if process.returncode:
sys.exit(f"scan failed:\n{err}")
run = json.loads(out.strip().splitlines()[-1])
run["wall"] = time.monotonic() - started
run["cpu_s"] = cpu_seconds(err)
run["machine"] = busy_percent(before, cpu_ticks())
return run
def main():
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("root", help="directory or volume to scan")
parser.add_argument("--workers", type=int, nargs="+", default=[18, 8, 4, 2])
parser.add_argument("--rounds", type=int, default=3)
parser.add_argument("--out", type=pathlib.Path, help="write every run as JSON here")
parser.add_argument("--lock", help="flock this file for the whole block")
args = parser.parse_args()
subprocess.run(
["cargo", "build", "--release", "-p", "disktree-core", "--example", "scan_workers"],
cwd=REPO,
check=True,
)
lock = open(args.lock, "w") if args.lock else None
if lock:
fcntl.flock(lock, fcntl.LOCK_EX)
cores = os.cpu_count() or 1
base = max(args.workers)
print(f"warm-up: {base} workers", file=sys.stderr)
scan(args.root, base)
runs = []
for round_ in range(args.rounds):
shift = round_ % len(args.workers)
order = args.workers[shift:] + args.workers[:shift]
if round_ % 2:
order.reverse()
for workers in order:
run = scan(args.root, workers)
run["round"] = round_ + 1
runs.append(run)
print(
f"round {round_ + 1}, {workers} workers: {run['elapsed']:.1f} s, "
f"{run['cpu_s']:.0f} CPU-s, machine {percent(run['machine'])}",
file=sys.stderr,
)
if args.out:
args.out.write_text(json.dumps(runs, indent=1))
def median(workers, key):
values = [r[key] for r in runs if r["workers"] == workers and r[key] is not None]
return statistics.median(values) if values else None
# The scan's own share of every core, which background load cannot move.
for run in runs:
run["share"] = 100 * run["cpu_s"] / (run["elapsed"] * cores)
b_time, b_cpu, b_share = (median(base, k) for k in ("elapsed", "cpu_s", "share"))
print(f"\nMedian of {args.rounds}; Δ against {base} workers; {cores} cores.\n")
print("| Workers | Scan time | Δ time | CPU time | Δ CPU time | Machine used | Δ machine | Whole machine |")
print("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |")
for workers in sorted(args.workers, reverse=True):
t, c, s, m = (median(workers, k) for k in ("elapsed", "cpu_s", "share", "machine"))
first = workers == base
pct = lambda x, y: "baseline" if first else f"{(x - y) / y * 100:+.0f}%"
pts = "baseline" if first else f"{s - b_share:+.0f} pts"
print(
f"| {workers} | {t:.0f} s | {pct(t, b_time)} | {c:,.0f} CPU-s | {pct(c, b_cpu)} "
f"| {s:.0f}% | {pts} | {percent(m)} |"
)
if __name__ == "__main__":
main()