chesspenguin --bench: timings of a database on this machine; memory probe via sysinfo

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-19 19:07:47 +03:00
parent a7d9d599aa
commit 1506ebdf26
8 changed files with 312 additions and 2 deletions

56
Cargo.lock generated
View file

@ -677,6 +677,7 @@ dependencies = [
"encoding_rs", "encoding_rs",
"sevenz-rust2", "sevenz-rust2",
"shakmaty", "shakmaty",
"sysinfo",
"thiserror 2.0.21", "thiserror 2.0.21",
"zip", "zip",
] ]
@ -2314,6 +2315,15 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "ntapi"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "num-bigint" name = "num-bigint"
version = "0.4.8" version = "0.4.8"
@ -2608,6 +2618,16 @@ dependencies = [
"objc2-core-foundation", "objc2-core-foundation",
] ]
[[package]]
name = "objc2-io-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
dependencies = [
"libc",
"objc2-core-foundation",
]
[[package]] [[package]]
name = "objc2-io-surface" name = "objc2-io-surface"
version = "0.3.2" version = "0.3.2"
@ -4001,6 +4021,20 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "sysinfo"
version = "0.39.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6"
dependencies = [
"libc",
"memchr",
"ntapi",
"objc2-core-foundation",
"objc2-io-kit",
"windows",
]
[[package]] [[package]]
name = "tar" name = "tar"
version = "0.4.46" version = "0.4.46"
@ -4871,6 +4905,22 @@ dependencies = [
"web-sys", "web-sys",
] ]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]] [[package]]
name = "winapi-util" name = "winapi-util"
version = "0.1.11" version = "0.1.11"
@ -4880,6 +4930,12 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "windows" name = "windows"
version = "0.62.2" version = "0.62.2"

View file

@ -24,6 +24,26 @@ mod viewed;
mod widgets; mod widgets;
fn main() -> eframe::Result { fn main() -> eframe::Result {
// `chesspenguin --bench <database> [report.txt]`: timings instead of the window
// (`docs/dev/import.md`, "Замер на другой машине").
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if args.first().is_some_and(|a| a == "--bench") {
let Some(db) = args.get(1) else {
eprintln!("usage: chesspenguin --bench <database> [report.txt]");
std::process::exit(2);
};
let cache = settings::Settings::cache_dir().map(|d| d.join("boosters"));
let result = match args.get(2) {
Some(file) => std::fs::File::create(file)
.and_then(|mut f| chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut f)),
None => chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut std::io::stdout()),
};
if let Err(e) = result {
eprintln!("bench: {e}");
std::process::exit(1);
}
return Ok(());
}
let options = eframe::NativeOptions { let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default() viewport: egui::ViewportBuilder::default()
.with_app_id("io.github.vrubelroman.chessPenguin") .with_app_id("io.github.vrubelroman.chessPenguin")

View file

@ -12,4 +12,5 @@ shakmaty.workspace = true
encoding_rs.workspace = true encoding_rs.workspace = true
thiserror.workspace = true thiserror.workspace = true
zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs", "deflate64", "bzip2"] } zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs", "deflate64", "bzip2"] }
sysinfo = { version = "0.39.6", default-features = false, features = ["system"] }
sevenz-rust2 = { version = "0.24.1", default-features = false, features = ["bzip2", "ppmd", "deflate"] } sevenz-rust2 = { version = "0.24.1", default-features = false, features = ["bzip2", "ppmd", "deflate"] }

View file

@ -0,0 +1,208 @@
//! `chesspenguin --bench <database> [report.txt]`: timings of opening, filtering and
//! position search in one database, to compare machines (laptops in particular) with
//! the numbers in `docs/dev/import.md`. Every search runs twice, so the first run
//! shows the cost of a cold file cache and the second the warm one. Nothing of the
//! database is written; a large ChessBase base without a usable `.cbb` gets our own
//! booster built in `booster_dir` (timed), as the application would do.
use std::io::{self, Write};
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::Instant;
use shakmaty::san::SanPlus;
use shakmaty::{Chess, Move, Position};
use crate::chessbase::base::{Filter, NameFilter, SortKey};
use crate::position::PositionQuery;
use crate::{Database, ScanProgress};
/// (name, moves from the start position).
const LINES: [(&str, &str); 5] = [
("start", ""),
("1.e4", "e4"),
("Najdorf, ply 10", "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6"),
(
"Nimzo-Indian, ply 20",
"d4 Nf6 c4 e6 Nc3 Bb4 e3 O-O Bd3 d5 Nf3 c5 O-O Nc6 a3 Bxc3 bxc3 dxc4 Bxc4 Qc7",
),
(
"Ruy Lopez, ply 40",
"e4 e5 Nf3 Nc6 Bb5 a6 Ba4 Nf6 O-O Be7 Re1 b5 Bb3 d6 c3 O-O h3 Nb8 d4 Nbd7 \
Nbd2 Bb7 Bc2 Re8 Nf1 Bf8 Ng3 g6 a4 c5 d5 c4 Bg5 h6 Be3 Nc5 Qd2 h5",
),
];
fn san_line(line: &str) -> Option<(Chess, Vec<Move>)> {
let mut pos = Chess::default();
let mut moves = Vec::new();
for s in line.split_whitespace() {
let m = s.parse::<SanPlus>().ok()?.san.to_move(&pos).ok()?;
moves.push(m);
pos.play_unchecked(m);
}
Some((pos, moves))
}
/// Peak resident memory of this process, where the system tells (Linux).
fn peak_memory() -> String {
std::fs::read_to_string("/proc/self/status")
.ok()
.and_then(|s| {
s.lines()
.find(|l| l.starts_with("VmHWM"))
.map(|l| l.trim_start_matches("VmHWM:").trim().to_owned())
})
.unwrap_or_else(|| "n/a".into())
}
fn mb(bytes: u64) -> String {
format!("{:.0} MB", bytes as f64 / 1e6)
}
/// Runs the measurements on the database at `path` and writes the report to `out`.
pub fn run(path: &Path, booster_dir: Option<&Path>, out: &mut dyn Write) -> io::Result<()> {
let never = AtomicBool::new(false);
let counter = AtomicUsize::new(0);
writeln!(
out,
"ChessPenguin {} bench · {} {} · {} threads · memory total {}, available {}",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH,
std::thread::available_parallelism().map_or(0, |n| n.get()),
crate::memory::total().map_or("n/a".into(), mb),
crate::memory::available().map_or("n/a".into(), mb),
)?;
writeln!(out, "{}", path.display())?;
let t = Instant::now();
let opened = crate::open(path, &mut |_: ScanProgress| {}, &never)
.map_err(|e| io::Error::other(e.to_string()))?;
let db = opened.db;
writeln!(
out,
"open: {:.2} s · {:?} · {} records · peak memory {}",
t.elapsed().as_secs_f64(),
opened.format,
db.len(),
peak_memory()
)?;
match &db {
Database::ChessBase(base) => {
if let Some(dir) = booster_dir {
base.set_booster_dir(dir);
}
let booster = if base.booster_ready() {
"yes".to_owned()
} else if base.booster_wanted() {
let t = Instant::now();
match base.build_booster(&counter, &never) {
Ok(true) => format!("built in {:.1} s", t.elapsed().as_secs_f64()),
Ok(false) => "cancelled".into(),
Err(e) => format!("failed: {e}"),
}
} else {
"none".into()
};
writeln!(out, "search booster (.cbb or our own): {booster}")?;
let carlsen = Filter {
player: NameFilter {
text: "carlsen, magnus".into(),
..NameFilter::default()
},
..Filter::default()
};
let t = Instant::now();
let selected = base
.query(&carlsen, SortKey::Date, false, &counter, &never)
.unwrap_or_default();
writeln!(
out,
"filter player \"carlsen, magnus\", newest first: {} games in {:.1} ms",
selected.len(),
t.elapsed().as_secs_f64() * 1e3
)?;
let t = Instant::now();
let all = base
.query(&Filter::default(), SortKey::White, true, &counter, &never)
.unwrap_or_default();
writeln!(
out,
"all {} records sorted by White: {:.1} ms",
all.len(),
t.elapsed().as_secs_f64() * 1e3
)?;
drop(all);
let mut candidates: Vec<u32> = selected;
candidates.sort_unstable();
writeln!(
out,
"position search (all games: first run, second run; then among the filtered games):"
)?;
for (name, line) in LINES {
let Some((pos, moves)) = san_line(line) else {
continue;
};
let query = PositionQuery::new(pos, Some(moves));
let mut cells = Vec::new();
let mut games = 0;
for cands in [None, None, Some(candidates.as_slice())] {
let t = Instant::now();
let found = db.search_position(cands, &query, &counter, &never);
let ms = t.elapsed().as_secs_f64() * 1e3;
let n = found.as_ref().map_or(0, |o| o.matches.len());
if cands.is_none() {
games = n;
}
cells.push(format!("{ms:8.1} ms"));
}
writeln!(
out,
" {name:22} {games:9} games {} {} filtered {}",
cells[0], cells[1], cells[2]
)?;
}
}
Database::Pgn(pgn) => {
writeln!(out, "games: {}", pgn.db.len())?;
let t = Instant::now();
let Some(table) = pgn.positions(&counter, &never) else {
return Ok(());
};
writeln!(
out,
"position table: {:.2} s · {} positions · {} · peak memory {}",
t.elapsed().as_secs_f64(),
table.positions(),
mb(table.memory() as u64),
peak_memory()
)?;
writeln!(out, "position search (first run, second run):")?;
for (name, line) in LINES {
let Some((pos, moves)) = san_line(line) else {
continue;
};
let query = PositionQuery::new(pos, Some(moves));
let mut cells = Vec::new();
let mut games = 0;
for _ in 0..2 {
let t = Instant::now();
let found = db.search_position(None, &query, &counter, &never);
cells.push(format!("{:8.1} ms", t.elapsed().as_secs_f64() * 1e3));
games = found.map_or(0, |o| o.matches.len());
}
writeln!(
out,
" {name:22} {games:9} games {} {}",
cells[0], cells[1]
)?;
}
}
}
writeln!(out, "peak memory: {}", peak_memory())?;
Ok(())
}

View file

@ -8,8 +8,10 @@
//! records and a game is converted to PGN when it is opened. Sources are only read. //! records and a game is converted to PGN when it is opened. Sources are only read.
mod archive; mod archive;
pub mod bench;
pub mod cbv; pub mod cbv;
pub mod chessbase; pub mod chessbase;
pub mod memory;
pub mod pgn_positions; pub mod pgn_positions;
pub mod position; pub mod position;
@ -104,7 +106,7 @@ impl PgnDb {
} }
/// The position table, built on first use. `None` when cancelled. /// The position table, built on first use. `None` when cancelled.
fn positions( pub(crate) fn positions(
&self, &self,
progress: &AtomicUsize, progress: &AtomicUsize,
cancel: &AtomicBool, cancel: &AtomicBool,

View file

@ -0,0 +1,19 @@
//! What the machine has: total and available memory, for choosing between keeping
//! an index in memory and reading it from disk (and for the bench report).
use sysinfo::{MemoryRefreshKind, RefreshKind, System};
fn system() -> System {
System::new_with_specifics(RefreshKind::nothing().with_memory(MemoryRefreshKind::everything()))
}
/// Bytes of memory the system reports as available to new allocations without
/// swapping (Linux `MemAvailable`; the other systems' equivalent). `None` when unknown.
pub fn available() -> Option<u64> {
Some(system().available_memory()).filter(|n| *n > 0)
}
/// Bytes of physical memory.
pub fn total() -> Option<u64> {
Some(system().total_memory()).filter(|n| *n > 0)
}

View file

@ -42,7 +42,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe
``` ```
`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии,
`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»).
## Языки ## Языки

View file

@ -99,6 +99,10 @@
На файлах пользователя (`pgnFilesforExample/`: 3 `.cbv` и 4 книги в `.7z`, всего ≈1900 записей) ни одной ошибки декодирования; все партии читаются обратно PGN-парсером без предупреждений (`tests/samples.rs`). На файлах пользователя (`pgnFilesforExample/`: 3 `.cbv` и 4 книги в `.7z`, всего ≈1900 записей) ни одной ошибки декодирования; все партии читаются обратно PGN-парсером без предупреждений (`tests/samples.rs`).
## Замер на другой машине
`chesspenguin --bench <база> [отчёт.txt]` (`crates/chess-import/src/bench.rs`) печатает отчёт вместо окна: система, потоки, память (всего / доступно, `memory.rs` через `sysinfo`), время открытия, для базы ChessBase — ускоритель (есть / построен за N с / нет), фильтр по игроку и сортировка всей базы, поиск пяти позиций (начальная, 1.e4, Найдорф, Нимцович на 20-м полуходе, испанская на 40-м) дважды подряд — первый прогон показывает холодный файловый кэш, второй тёплый — и среди партий игрока; для PGN — построение таблицы позиций и те же поиски. На Windows релизная сборка без консоли, поэтому там нужен второй аргумент с файлом отчёта. Ничего в базу не пишется; свой ускоритель, если он нужен, строится в кэше приложения, как и в окне. Так сравниваются ноутбуки с числами выше (i7-13700KF, 24 потока): на нём Mega открывается за 0,55 с, фильтр по Карлсену 46 мс, сортировка всей базы по белым 0,39 с, начальная позиция 0,39 с, Найдорф 80 мс, глубокие позиции 16–21 мс, среди партий Карлсена 1–5 мс.
## Проверка ## Проверка
```sh ```sh