From 109e1d1839b98cb4c9e15d3bffa2d9950d4f3e9b Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 27 Oct 2026 07:12:56 +0300 Subject: [PATCH] voelin-gpui: the cost meter as a development switch (VOELIN_METER=1), logged once a second meter.rs is spike_common::meter of the GPUI spikes (spikes/gpui/common/src/meter.rs, docs/design/gpui-spikes.md) without the measuring run's summary and exit: once a second, on a thread of its own, a log line (target voelin_gpui::meter, level info) with the process's CPU in percent of one core, the resident memory, the CPU of each group of threads (a thread's name without its trailing number: `llvmpipe-12` is `llvmpipe`, which tells the software renderer's share, work a GPU would take, from GPUI's thread, the engine's runtime and the codecs; the busiest first, groups under 0.5 % left out), the app's own counters per second and the voice connections as a gauge: cpu 11.9% rss 250.4 MiB | threads llvmpipe 5.9 voelin-gpui 5.0 | engine_events 0.0/s ticks 1.0/s renders 1.0/s later_jobs 0.0/s | connections 0 The counters (`Counters`: engine events handled, ticks, renders, jobs run through `Later`, connections up) are shared with the root state and the main view, which count in `handle_event`, `tick`, the later task and `render`; the numbers come from /proc/self (a note and a warning say so where there is none; rustix's `param` for the page size and the clock tick, Linux only, no new package: the lock gains the edge). The line is a pure function with a test, as are the thread grouping and the stat parser (a name with spaces and parentheses), and one test reads this process and checks it has threads and memory. The root state's tests now also check the counters (events, the connection gauge, three ticks, a job from another thread). `VOELIN_METER=1` starts it (dev.rs parses it with the other switches). Running the debug binary on the swatch page on Xvfb :97 logs the lines above (about 12 % of a core when idle, the software renderer 6 to 11 % of it, one frame a second); the window closes with exit code 0. The default log filter now leaves out GPUI's "failed to load font .SystemUIFont" warning, which every start printed (gpui-component asks for the platform UI font before the theme names Inter; the text system falls back). Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets), `cargo test -p voelin-gpui` (30 tests), cargo deny, `scripts/notices.sh --check`. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 3 +- Cargo.lock | 1 + crates/voelin-gpui/Cargo.toml | 4 + crates/voelin-gpui/src/app.rs | 36 +++- crates/voelin-gpui/src/dev.rs | 10 +- crates/voelin-gpui/src/lib.rs | 34 +++- crates/voelin-gpui/src/meter.rs | 287 ++++++++++++++++++++++++++++++++ crates/voelin-gpui/src/view.rs | 6 +- 8 files changed, 362 insertions(+), 19 deletions(-) create mode 100644 crates/voelin-gpui/src/meter.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b7803eb..56579db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,8 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows `system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows every token, a few widgets and the icons (`VOELIN_DEV_THEME`, `VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with - `scripts/gpui-shot.sh`, docs/ui/). The Slint app (`voelin`) is unchanged and + `scripts/gpui-shot.sh`, docs/ui/). `VOELIN_METER=1` logs what it costs once a + second: the CPU by group of threads, the memory and its own counters. The Slint app (`voelin`) is unchanged and stays the app; both run on one engine until the GPUI one reaches parity (docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders in software); no package ships it yet. diff --git a/Cargo.lock b/Cargo.lock index 8622a05..eb020f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12584,6 +12584,7 @@ dependencies = [ "anyhow", "gpui-kit", "gpui-pre", + "rustix 1.1.5", "tokio", "tracing", "tracing-subscriber", diff --git a/crates/voelin-gpui/Cargo.toml b/crates/voelin-gpui/Cargo.toml index def0740..091ea3e 100644 --- a/crates/voelin-gpui/Cargo.toml +++ b/crates/voelin-gpui/Cargo.toml @@ -36,6 +36,10 @@ voelin-store = { path = "../voelin-store" } # The view models and the state, shared with the Slint front end. voelin-ui-vm = { path = "../voelin-ui-vm" } +# The meter reads /proc/self (CPU ticks per second, the page size). +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { version = "1.1.5", features = ["param"] } + [dev-dependencies] # GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests # need no display. gpui-kit's own `test-support` feature is not used: it names diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index 829eb60..69bab22 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -31,6 +31,8 @@ use voelin_ui_vm::host::{Host, Update}; use voelin_ui_vm::settings::UiSettings; use voelin_ui_vm::social::logic::Social; +use crate::meter::Counters; + /// The toolkit-free state of the client, with the chat lines of a tab as plain /// rows (what a front end that draws again from the list needs). pub type VmState = voelin_ui_vm::state::AppState>; @@ -120,6 +122,7 @@ pub struct AppState { engine: Option, host: ShellHost, started: Instant, + counters: Counters, later: Later, } @@ -130,6 +133,7 @@ impl AppState { pub fn new( engine: Option, events: UnboundedReceiver, + counters: Counters, cx: &mut Context, ) -> Self { let (later, mut jobs) = mpsc::unbounded_channel::(); @@ -158,6 +162,7 @@ impl AppState { while let Some(job) = jobs.recv().await { if this .update(cx, |state, cx| { + state.counters.later_jobs.incr(); job(state, cx); cx.notify(); }) @@ -182,6 +187,7 @@ impl AppState { engine, host: ShellHost, started: Instant::now(), + counters, later: Later(later), } } @@ -195,8 +201,10 @@ impl AppState { /// dispatch of both front ends), and what comes of it for the engine. pub fn handle_event(&mut self, event: Event, cx: &mut Context) { self.events_handled += 1; + self.counters.engine_events.incr(); let update = events::handle(&mut self.vm, &mut self.social, &self.host, event); self.perform(update); + self.counters.connections.set(self.connections() as u64); cx.notify(); } @@ -217,6 +225,7 @@ impl AppState { /// here (stream statistics, stored settings); today it counts. pub fn tick(&mut self, cx: &mut Context) { self.ticks += 1; + self.counters.ticks.incr(); cx.notify(); } @@ -275,15 +284,21 @@ mod tests { /// The entity of a test with no engine behind it: `tx` stands in for the /// engine's events. - fn entity(cx: &mut TestAppContext) -> (gpui_kit::Entity, UnboundedSender) { + fn entity( + cx: &mut TestAppContext, + ) -> (gpui_kit::Entity, UnboundedSender, Counters) { let (tx, rx) = mpsc::unbounded_channel(); - let app = cx.new(move |cx| AppState::new(None, rx, cx)); - (app, tx) + let counters = Counters::default(); + let app = cx.new({ + let counters = counters.clone(); + move |cx| AppState::new(None, rx, counters, cx) + }); + (app, tx, counters) } #[gpui::test] fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) { - let (app, tx) = entity(cx); + let (app, tx, counters) = entity(cx); app.read_with(cx, |app, _| { assert_eq!(app.connections(), 0); assert!(app.state_line().contains("0 connections ยท 0 engine events")); @@ -301,6 +316,8 @@ mod tests { app.state_line() ); }); + assert_eq!(counters.engine_events.get(), 1); + assert_eq!(counters.connections.get(), 1); tx.send(voice(VoiceState::Disconnected)).unwrap(); cx.run_until_parked(); @@ -311,7 +328,7 @@ mod tests { #[gpui::test] fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) { - let (app, tx) = entity(cx); + let (app, tx, _) = entity(cx); let notified = std::rc::Rc::new(std::cell::Cell::new(0)); let _subscription = cx.update(|cx| { let notified = notified.clone(); @@ -324,7 +341,7 @@ mod tests { #[gpui::test] fn the_tick_runs_once_a_second(cx: &mut TestAppContext) { - let (app, _tx) = entity(cx); + let (app, _tx, counters) = entity(cx); cx.run_until_parked(); assert_eq!(app.read_with(cx, |app, _| app.ticks), 0); for second in 1..=3 { @@ -332,11 +349,12 @@ mod tests { cx.run_until_parked(); assert_eq!(app.read_with(cx, |app, _| app.ticks), second); } + assert_eq!(counters.ticks.get(), 3); } #[gpui::test] fn another_thread_runs_a_job_on_the_entity_through_later(cx: &mut TestAppContext) { - let (app, _tx) = entity(cx); + let (app, _tx, counters) = entity(cx); let later = app.read_with(cx, |app, _| app.later()); let sent = std::thread::spawn(move || { later.run(|app, _| app.vm.status = "from another thread".into()) @@ -346,6 +364,7 @@ mod tests { assert!(sent); cx.run_until_parked(); assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "from another thread"); + assert_eq!(counters.later_jobs.get(), 1); } /// The whole path with a real engine: a command makes the engine report a @@ -366,7 +385,8 @@ mod tests { .unwrap(); let hosted = HostedEngine::start(&runtime); let engine = hosted.engine.clone(); - let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, cx)); + let counters = Counters::default(); + let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, counters, cx)); engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() }); let deadline = Instant::now() + Duration::from_secs(120); while app.read_with(cx, |app, _| app.events_handled) == 0 { diff --git a/crates/voelin-gpui/src/dev.rs b/crates/voelin-gpui/src/dev.rs index c844482..527bf0f 100644 --- a/crates/voelin-gpui/src/dev.rs +++ b/crates/voelin-gpui/src/dev.rs @@ -11,6 +11,8 @@ //! one the settings will give (`ui.theme` in the Slint front end). //! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`). //! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size. +//! - `VOELIN_METER=1`: the cost meter, one log line a second +//! ([`crate::meter`]). use crate::theme::Choice; @@ -34,11 +36,13 @@ pub struct Switches { pub font_scale: Option, /// The window's size in pixels, when the switch names one. pub window: Option<(f32, f32)>, + /// Log the cost meter. + pub meter: bool, } impl Default for Switches { fn default() -> Self { - Self { open: Page::Shell, theme: None, font_scale: None, window: None } + Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false } } } @@ -80,6 +84,7 @@ impl Switches { None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"), } } + switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0")); switches } } @@ -115,11 +120,13 @@ mod tests { ("VOELIN_DEV_THEME", "light"), ("VOELIN_FONT_SCALE", "1.25"), ("VOELIN_WINDOW_SIZE", "1440x960"), + ("VOELIN_METER", "1"), ]); assert_eq!(s.open, Page::Swatch); assert_eq!(s.theme, Some(Choice::Light)); assert_eq!(s.font_scale, Some(1.25)); assert_eq!(s.window, Some((1440.0, 960.0))); + assert!(s.meter); } #[test] @@ -129,6 +136,7 @@ mod tests { ("VOELIN_DEV_THEME", "blue"), ("VOELIN_FONT_SCALE", "9"), ("VOELIN_WINDOW_SIZE", "10x10"), + ("VOELIN_METER", "0"), ]); assert_eq!(s, Switches::default()); } diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index cd4769f..76743b0 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -10,6 +10,7 @@ pub mod assets; pub mod dev; pub mod engine; pub mod fonts; +pub mod meter; pub mod swatch; pub mod theme; pub mod view; @@ -26,15 +27,20 @@ use crate::app::AppState; use crate::assets::Assets; use crate::dev::Switches; use crate::engine::HostedEngine; +use crate::meter::Counters; use crate::theme::{Choice, VoelinTheme}; use crate::view::MainView; /// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every /// crate, this front end's information, and what GPUI says about the display -/// and the GPU adapter it picked (which device a run used). zbus's warnings -/// are left out, as in the Slint front end: it warns when a desktop portal's -/// request object is gone before it reads its properties, which is harmless. -const LOG_FILTER: &str = "warn,zbus=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info"; +/// and the GPU adapter it picked (which device a run used). Two warnings are +/// left out because they are harmless: zbus's, as in the Slint front end (it +/// warns when a desktop portal's request object is gone before it reads its +/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component +/// asks for the platform's UI font, which Linux has no name for, before the +/// theme names Inter; the text system falls back). +const LOG_FILTER: &str = + "warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info"; /// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`]. /// GPUI logs through the `log` crate; the subscriber carries those records. @@ -65,9 +71,17 @@ fn window_options(switches: &Switches, cx: &App) -> WindowOptions { /// Open the main window on the root state; closing it leaves the servers and /// ends the app. -fn open_main_window(cx: &mut App, switches: &Switches, engine: HostedEngine) -> Result<()> { +fn open_main_window( + cx: &mut App, + switches: &Switches, + engine: HostedEngine, + counters: Counters, +) -> Result<()> { let HostedEngine { engine, events, .. } = engine; - let app = cx.new(move |cx| AppState::new(Some(engine), events, cx)); + let app = cx.new({ + let counters = counters.clone(); + move |cx| AppState::new(Some(engine), events, counters, cx) + }); let options = window_options(switches, cx); let page = switches.open; gpui_kit::open_window(options, cx, { @@ -84,7 +98,7 @@ fn open_main_window(cx: &mut App, switches: &Switches, engine: HostedEngine) -> true } }); - cx.new(|cx| MainView::new(app, page, window, cx)) + cx.new(|cx| MainView::new(app, page, counters, window, cx)) } }) .context("cannot open the main window")?; @@ -100,6 +114,10 @@ pub fn run() -> Result<()> { os = std::env::consts::OS, "Voelin (GPUI) starting" ); + let counters = Counters::default(); + if switches.meter { + meter::start(counters.clone()); + } // The engine runs on tokio threads of its own; the window is GPUI's. let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() @@ -120,7 +138,7 @@ pub fn run() -> Result<()> { cx.window_appearance(), switches.font_scale.unwrap_or(1.0), ); - if let Err(e) = open_main_window(cx, &switches, hosted) { + if let Err(e) = open_main_window(cx, &switches, hosted, counters) { *failure.borrow_mut() = Some(e); cx.quit(); } diff --git a/crates/voelin-gpui/src/meter.rs b/crates/voelin-gpui/src/meter.rs new file mode 100644 index 0000000..1fe6596 --- /dev/null +++ b/crates/voelin-gpui/src/meter.rs @@ -0,0 +1,287 @@ +//! What the app costs, once a second, in the log: the CPU of the process and +//! of each group of threads, the resident memory, and the app's own counters +//! (a development switch, `VOELIN_METER=1`, so that every slice can say what +//! it costs). It is `spike_common::meter` of the GPUI spikes +//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the +//! measuring run's summary and exit, writing log lines instead of JSON. +//! +//! CPU is in percent of one core (200 means two cores busy). Threads are +//! grouped by name without a trailing number (`llvmpipe-12` becomes +//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*` +//! threads, work a GPU would take over) from GPUI's thread, the engine's +//! runtime and the codecs. The numbers come from `/proc/self`: on other +//! systems the meter says it cannot read them and stops. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// A number the app counts up (events handled, frames drawn) or sets (open +/// connections); the meter reports counters per second and gauges as they +/// are. +#[derive(Clone, Default, Debug)] +pub struct Counter(Arc); + +impl Counter { + /// Add one. + pub fn incr(&self) { + self.0.fetch_add(1, Ordering::Relaxed); + } + + /// Set (gauges). + pub fn set(&self, value: u64) { + self.0.store(value, Ordering::Relaxed); + } + + /// The current value. + pub fn get(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } +} + +/// The app's own numbers the meter reports besides the process's. +#[derive(Clone, Default, Debug)] +pub struct Counters { + /// Engine events handled by the root state (per second). + pub engine_events: Counter, + /// One-second ticks of the root state (per second: 1). + pub ticks: Counter, + /// Windows drawn (frames, per second). + pub renders: Counter, + /// Jobs other threads handed to the foreground through + /// [`crate::app::Later`] (per second). + pub later_jobs: Counter, + /// Voice connections that are up (a gauge). + pub connections: Counter, +} + +/// CPU ticks of the process and of each thread group, and the resident +/// memory, at one moment. +#[derive(Clone, Debug)] +pub struct Snapshot { + at: Instant, + process: u64, + threads: BTreeMap, + rss_bytes: u64, +} + +/// The size of a page of memory, for `statm`'s page counts. +#[cfg(target_os = "linux")] +fn page_size() -> u64 { + rustix::param::page_size() as u64 +} + +/// The size of a page of memory (Linux only matters: `/proc`). +#[cfg(not(target_os = "linux"))] +fn page_size() -> u64 { + 4096 +} + +/// The unit of the CPU times in `stat`. +#[cfg(target_os = "linux")] +fn clock_ticks_per_second() -> u64 { + rustix::param::clock_ticks_per_second() +} + +/// The unit of the CPU times in `stat` (Linux only matters: `/proc`). +#[cfg(not(target_os = "linux"))] +fn clock_ticks_per_second() -> u64 { + 100 +} + +/// `utime + stime` and the name of a `/proc/.../stat` line. +fn ticks_of(stat: &str) -> Option<(String, u64)> { + let open = stat.find('(')?; + let close = stat.rfind(')')?; + let name = stat.get(open + 1..close)?.to_owned(); + let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect(); + // Fields 14 and 15 of proc(5); the remainder starts at field 3. + let utime: u64 = fields.get(11)?.parse().ok()?; + let stime: u64 = fields.get(12)?.parse().ok()?; + Some((name, utime + stime)) +} + +/// A thread's group: its name without a trailing number or separator. +pub fn group_of(name: &str) -> String { + let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit()); + let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']); + if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() } +} + +impl Snapshot { + /// Read `/proc/self` now; `None` where there is none. + pub fn now() -> Option { + let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1; + let mut threads = BTreeMap::new(); + if let Ok(dir) = std::fs::read_dir("/proc/self/task") { + for entry in dir.flatten() { + let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue }; + if let Some((name, ticks)) = ticks_of(&stat) { + *threads.entry(group_of(&name)).or_insert(0) += ticks; + } + } + } + let rss_bytes = std::fs::read_to_string("/proc/self/statm") + .ok() + .and_then(|s| s.split_whitespace().nth(1)?.parse::().ok()) + .map_or(0, |pages| pages * page_size()); + Some(Self { at: Instant::now(), process, threads, rss_bytes }) + } + + /// Resident memory in MiB. + pub fn rss_mib(&self) -> f64 { + self.rss_bytes as f64 / (1024.0 * 1024.0) + } +} + +/// CPU in percent of one core between two snapshots: the process's and each +/// thread group's that used any (groups that exited in between count from +/// zero). +pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap) { + let hz = clock_ticks_per_second() as f64; + let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6); + let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0; + let process = pct(b.process.saturating_sub(a.process)); + let threads = b + .threads + .iter() + .map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0))))) + .filter(|(_, p)| *p > 0.0) + .collect(); + (process, threads) +} + +/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads +/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`. +pub fn line( + cpu: f64, + rss_mib: f64, + threads: &BTreeMap, + rates: &[(&str, f64)], + gauges: &[(&str, u64)], +) -> String { + let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB"); + // The busiest groups first; a thread group under 0.5 % is noise. + let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect(); + busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0))); + if !busy.is_empty() { + text.push_str(" | threads"); + for (name, pct) in busy { + let _ = write!(text, " {name} {pct:.1}"); + } + } + text.push_str(" |"); + for (name, rate) in rates { + let _ = write!(text, " {name} {rate:.1}/s"); + } + if !gauges.is_empty() { + text.push_str(" |"); + for (name, value) in gauges { + let _ = write!(text, " {name} {value}"); + } + } + text +} + +/// Start the meter on a thread of its own: once a second, a log line (target +/// `voelin_gpui::meter`, level info) with the process's CPU and memory and +/// `counters`' rates. It ends with the process. +pub fn start(counters: Counters) { + let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || { + let Some(mut last) = Snapshot::now() else { + tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here"); + return; + }; + let rated = [ + ("engine_events", counters.engine_events.clone()), + ("ticks", counters.ticks.clone()), + ("renders", counters.renders.clone()), + ("later_jobs", counters.later_jobs.clone()), + ]; + let mut last_counts: Vec = rated.iter().map(|(_, c)| c.get()).collect(); + tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)"); + loop { + std::thread::sleep(Duration::from_secs(1)); + let Some(now) = Snapshot::now() else { return }; + let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6); + let (cpu, threads) = cpu_between(&last, &now); + let counts: Vec = rated.iter().map(|(_, c)| c.get()).collect(); + let rates: Vec<(&str, f64)> = rated + .iter() + .zip(counts.iter().zip(&last_counts)) + .map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs)) + .collect(); + let gauges = [("connections", counters.connections.get())]; + tracing::info!( + target: "voelin_gpui::meter", + "{}", + line(cpu, now.rss_mib(), &threads, &rates, &gauges) + ); + last = now; + last_counts = counts; + } + }); + if let Err(error) = spawned { + tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn groups_drop_trailing_numbers() { + assert_eq!(group_of("llvmpipe-12"), "llvmpipe"); + assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w"); + assert_eq!(group_of("voelin-meter"), "voelin-meter"); + assert_eq!(group_of("1234"), "1234"); + } + + #[test] + fn stat_lines_parse_with_spaces_in_names() { + let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0"; + assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123))); + } + + #[test] + fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() { + let threads = BTreeMap::from([ + ("main".to_owned(), 5.04), + ("llvmpipe".to_owned(), 310.0), + ("idle".to_owned(), 0.2), + ]); + let text = line( + 317.0, + 210.44, + &threads, + &[("engine_events", 0.0), ("renders", 59.96)], + &[("connections", 1)], + ); + assert_eq!( + text, + "cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1" + ); + } + + #[test] + fn this_process_can_be_read_on_linux() { + if !cfg!(target_os = "linux") { + return; + } + let a = Snapshot::now().expect("/proc/self"); + // Burn a little CPU on this thread so that the process has some to show. + let started = Instant::now(); + let mut x = 0u64; + while started.elapsed() < Duration::from_millis(60) { + x = x.wrapping_mul(31).wrapping_add(7); + } + std::hint::black_box(x); + let b = Snapshot::now().expect("/proc/self"); + let (cpu, threads) = cpu_between(&a, &b); + assert!(cpu >= 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib()); + assert!(!threads.is_empty()); + } +} diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index bf87172..2886a40 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -9,6 +9,7 @@ use gpui_kit::{ use crate::app::AppState; use crate::dev::Page; +use crate::meter::Counters; use crate::swatch::swatch; use crate::theme::{VoelinTheme, hsla}; @@ -16,6 +17,7 @@ use crate::theme::{VoelinTheme, hsla}; pub struct MainView { app: Entity, page: Page, + counters: Counters, } impl MainView { @@ -24,6 +26,7 @@ impl MainView { pub fn new( app: Entity, page: Page, + counters: Counters, window: &mut Window, cx: &mut Context, ) -> Self { @@ -32,12 +35,13 @@ impl MainView { VoelinTheme::set_system_appearance(cx, window.appearance()); }) .detach(); - Self { app, page } + Self { app, page, counters } } } impl Render for MainView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.counters.renders.incr(); let line = self.app.read(cx).state_line(); let theme = VoelinTheme::global(cx).clone(); let (c, m) = (&theme.colors, &theme.metrics);