Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / map / src / main / rust / tests / frame_cpu_bench.rs

frame_cpu_bench.rs377 lines · 14.7 KiBRaw
1//! Host timings for the work the map used to do on the Android main thread.
2//!
3//! Not a correctness test: ignored by default and run on demand to put numbers on the
4//! render-thread move and on the hot paths it carries. Everything here is the CPU half of the
5//! native renderer (the Vulkan half has no host build), timed on the host with the same code
6//! the device runs. A phone core is roughly 2-4x slower than a desktop core, so read these as
7//! lower bounds for the device.
8//!
9//! ```text
10//! cargo test -p map_renderer --release --test frame_cpu_bench -- --ignored --nocapture --test-threads=1
11//! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps cargo test ... (adds the archive half)
12//! ```
13
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18use map_renderer::camera::Camera;
19use map_renderer::style::{self, KindFilter, LayerToggles};
20use map_renderer::tile::geometry;
21use map_renderer::tile::glyph::atlas::GlyphAtlas;
22use map_renderer::tile::select;
23use map_renderer::tile::source::FileRangeReader;
24use map_renderer::tile::sprite::SpriteAtlas;
25use tilecodec::mamaps::read::{LeafCache, MamapsArchive};
26
27fn ms(d: Duration) -> f64 {
28 d.as_secs_f64() * 1e3
29}
30
31fn camera(lon: f64, lat: f64, zoom: f64) -> Camera {
32 Camera {
33 center_lon: lon,
34 center_lat: lat,
35 zoom,
36 // A Pixel-class portrait viewport.
37 width_dp: 412.0,
38 height_dp: 915.0,
39 density: 2.625,
40 bearing_deg: 0.0,
41 pitch_deg: 0.0,
42 pivot_dp: 0.0,
43 globe: false,
44 moon: false,
45 time_seconds: 0.0,
46 }
47}
48
49/// What `MapNative.create` computed on the calling thread before any Vulkan object existed:
50/// the parsed style, the SDF glyph atlas and the decoded POI sprite sheet. All three are
51/// process-wide lazies, so this is a first-surface cost (each process pays it once).
52#[test]
53#[ignore = "timing harness; run with --ignored --nocapture"]
54fn create_time_cpu_work() {
55 let t = Instant::now();
56 let layers = style::layers().len();
57 let style_ms = ms(t.elapsed());
58 let t = Instant::now();
59 let glyphs = GlyphAtlas::build();
60 let atlas_ms = ms(t.elapsed());
61 let t = Instant::now();
62 let sprites = SpriteAtlas::build().expect("sprite sheet");
63 let sprite_ms = ms(t.elapsed());
64 std::hint::black_box((&glyphs, &sprites));
65 println!(
66 "create CPU work: style parse {style_ms:.1} ms ({layers} layers), glyph atlas {atlas_ms:.1} ms, \
67 sprite decode {sprite_ms:.1} ms, total {:.1} ms",
68 style_ms + atlas_ms + sprite_ms
69 );
70}
71
72/// Per-frame tile selection (`select::visible` + `select::resident_set`), which `render` runs
73/// on every frame while the camera moves.
74#[test]
75#[ignore = "timing harness; run with --ignored --nocapture"]
76fn per_frame_selection() {
77 for zoom in [4.0, 10.0, 14.0, 17.0] {
78 let mut cam = camera(-122.4194, 37.7749, zoom);
79 let frames = 2_000;
80 let t = Instant::now();
81 let mut n = 0usize;
82 for i in 0..frames {
83 // A pan: a little east every frame, as a drag does.
84 cam.center_lon = -122.4194 + i as f64 * 1e-5 * 2f64.powf(14.0 - zoom);
85 n += select::visible(&cam, 0, 15).len();
86 n += select::resident_set(&cam, 0, 15).len();
87 }
88 println!(
89 "selection z{zoom}: {:.3} ms/frame ({} tiles/frame)",
90 ms(t.elapsed()) / frames as f64,
91 n / frames
92 );
93 }
94}
95
96fn archive_path() -> Option<PathBuf> {
97 match std::env::var("MAMAPS_REAL_ARCHIVE") {
98 Ok(p) if Path::new(&p).is_file() => Some(PathBuf::from(p)),
99 _ => {
100 eprintln!("MAMAPS_REAL_ARCHIVE not set: archive half skipped");
101 None
102 }
103 }
104}
105
106/// Worker-side cost of one viewport: archive read (memory-mapped, cold pages are random
107/// reads) plus decode and tessellation per tile. Runs on the tile workers, never on the
108/// render or main thread; reported so the frame numbers have their background counterpart.
109#[test]
110#[ignore = "needs MAMAPS_REAL_ARCHIVE; timing harness"]
111fn viewport_tile_build() {
112 let Some(path) = archive_path() else { return };
113 let archive = MamapsArchive::open_with_cache(
114 FileRangeReader::open(&path).expect("open"),
115 Arc::new(LeafCache::new()),
116 )
117 .expect("archive");
118 let layers = style::layers();
119 let toggles = LayerToggles { poi: true, transit: true, traffic: true, safety: true };
120 for (name, lon, lat, zoom) in
121 [("SF", -122.4194, 37.7749, 14.0), ("London", -0.1278, 51.5074, 11.0)]
122 {
123 let cam = camera(lon, lat, zoom);
124 let tiles = select::visible(&cam, archive.header.min_zoom, archive.header.max_zoom);
125 let (mut read, mut build, mut labels) = (Duration::ZERO, Duration::ZERO, 0usize);
126 for tile in &tiles {
127 let t = Instant::now();
128 let Ok(Some(body)) = archive.tile(tile.z, tile.x, tile.y) else { continue };
129 read += t.elapsed();
130 let t = Instant::now();
131 let mesh = geometry::build_toggled(
132 &body,
133 layers,
134 tile.z,
135 tile.x,
136 tile.y,
137 false,
138 toggles,
139 &KindFilter::all(),
140 1,
141 );
142 build += t.elapsed();
143 labels += mesh.labels.len();
144 }
145 println!(
146 "{name} z{zoom}: {} tiles, read {:.1} ms, decode+tessellate {:.1} ms ({:.1} ms/tile), {labels} labels",
147 tiles.len(),
148 ms(read),
149 ms(build),
150 ms(build) / tiles.len().max(1) as f64
151 );
152 }
153}
154
155/// The per-frame label bookkeeping in `record_symbol`: for every symbol layer, every tile's
156/// whole label list is scanned for that layer's labels (once to count, once to emit), and each
157/// of those pays a `candidate_id` + accept-set lookup before any glyph is emitted.
158#[test]
159#[ignore = "needs MAMAPS_REAL_ARCHIVE; timing harness"]
160fn per_frame_label_scan() {
161 use map_renderer::style::LayerKind;
162 use map_renderer::tile::placement::candidate_id;
163 use std::collections::HashMap;
164 let Some(path) = archive_path() else { return };
165 let archive = MamapsArchive::open_with_cache(
166 FileRangeReader::open(&path).expect("open"),
167 Arc::new(LeafCache::new()),
168 )
169 .expect("archive");
170 let layers = style::layers();
171 let symbol_layers: Vec<usize> =
172 (0..layers.len()).filter(|&i| layers[i].kind == LayerKind::Symbol).collect();
173 let toggles = LayerToggles { poi: true, transit: true, traffic: true, safety: true };
174 for (name, lon, lat, zoom) in
175 [("SF", -122.4194, 37.7749, 14.0), ("London", -0.1278, 51.5074, 11.0)]
176 {
177 let cam = camera(lon, lat, zoom);
178 let tiles: Vec<_> = select::visible(&cam, archive.header.min_zoom, archive.header.max_zoom)
179 .into_iter()
180 .filter_map(|t| {
181 let body = archive.tile(t.z, t.x, t.y).ok()??;
182 Some(geometry::build_toggled(
183 &body,
184 layers,
185 t.z,
186 t.x,
187 t.y,
188 false,
189 toggles,
190 &KindFilter::all(),
191 1,
192 ))
193 })
194 .collect();
195 let total: usize = tiles.iter().map(|m| m.labels.len()).sum();
196 // ~1 label in 20 survives placement at these zooms; the accept set is what is looked up.
197 let mut accepted: HashMap<u64, (bool, u32)> = HashMap::new();
198 for m in &tiles {
199 for (i, l) in m.labels.iter().enumerate() {
200 if i % 20 == 0 {
201 accepted.insert(candidate_id(m.z, m.x, m.y, l.layer_index, i), (false, 0));
202 }
203 }
204 }
205 let frames = 200;
206 let t = Instant::now();
207 let mut hits = 0usize;
208 for _ in 0..frames {
209 for &layer_index in &symbol_layers {
210 for m in &tiles {
211 let count = m.labels.iter().filter(|l| l.layer_index == layer_index).count();
212 std::hint::black_box(count);
213 for (i, l) in
214 m.labels.iter().enumerate().filter(|(_, l)| l.layer_index == layer_index)
215 {
216 if accepted.contains_key(&candidate_id(m.z, m.x, m.y, layer_index, i)) {
217 hits += 1;
218 }
219 std::hint::black_box(l);
220 }
221 }
222 }
223 }
224 let scan_ms = ms(t.elapsed()) / frames as f64;
225 // The same walk through the per-tile layer index the renderer now builds at upload,
226 // against the accept-set as the renderer now keys it (ids pass straight through).
227 let indexed: Vec<_> = tiles.iter().map(|m| geometry::labels_by_layer(&m.labels)).collect();
228 let accepted: map_renderer::tile::placement::CandidateMap<(bool, u32)> =
229 accepted.iter().map(|(k, v)| (*k, *v)).collect();
230 let t = Instant::now();
231 let mut hits_indexed = 0usize;
232 for _ in 0..frames {
233 for &layer_index in &symbol_layers {
234 for (m, index) in tiles.iter().zip(&indexed) {
235 let own = index.get(&layer_index).map_or(&[][..], Vec::as_slice);
236 std::hint::black_box(own.len());
237 for &i in own {
238 let l = &m.labels[i as usize];
239 if accepted.contains_key(&candidate_id(
240 m.z,
241 m.x,
242 m.y,
243 layer_index,
244 i as usize,
245 )) {
246 hits_indexed += 1;
247 }
248 std::hint::black_box(l);
249 }
250 }
251 }
252 }
253 let indexed_ms = ms(t.elapsed()) / frames as f64;
254 assert_eq!(hits, hits_indexed, "the index must visit exactly the same labels");
255 println!(
256 "{name} z{zoom}: {total} labels x {} symbol layers: filter scan {scan_ms:.3} ms/frame, \
257 layer index + id-keyed set {indexed_ms:.3} ms/frame ({} accepted)",
258 symbol_layers.len(),
259 hits / frames
260 );
261 }
262}
263
264/// What the tile workers' nice value does to a frame thread under a tile burst.
265///
266/// Eight busy "workers" (the native tile-worker count) and one frame thread that needs 4 ms of
267/// CPU every 16.7 ms, squeezed onto two cores so they contend the way a pan's tile burst
268/// contends a phone's cores. Run under `taskset -c 0-1`. Reports the frame thread's wall time
269/// per frame with the workers at nice 0 (before) and nice 10 (after,
270/// `bridge::priority::WORKER_NICE`).
271#[test]
272#[ignore = "scheduler harness; run under `taskset -c 0-1` with --ignored --nocapture"]
273fn worker_priority_vs_frame_time() {
274 use std::sync::atomic::{AtomicBool, Ordering};
275 extern "C" {
276 fn setpriority(which: i32, who: u32, prio: i32) -> i32;
277 }
278 fn spin(d: Duration) {
279 let t = Instant::now();
280 while t.elapsed() < d {
281 std::hint::spin_loop();
282 }
283 }
284 for nice in [0, 10] {
285 let stop = Arc::new(AtomicBool::new(false));
286 let workers: Vec<_> = (0..8)
287 .map(|_| {
288 let stop = Arc::clone(&stop);
289 std::thread::spawn(move || {
290 unsafe { setpriority(0, 0, nice) };
291 while !stop.load(Ordering::Relaxed) {
292 spin(Duration::from_millis(1));
293 }
294 })
295 })
296 .collect();
297 std::thread::sleep(Duration::from_millis(100));
298 let mut walls = Vec::new();
299 let period = Duration::from_micros(16_667);
300 let start = Instant::now();
301 for frame in 0..120u32 {
302 let due = start + period * frame;
303 if let Some(wait) = due.checked_duration_since(Instant::now()) {
304 std::thread::sleep(wait);
305 }
306 let t = Instant::now();
307 // 4 ms of frame work (recording, placement, emission).
308 spin(Duration::from_millis(4));
309 walls.push(t.elapsed());
310 }
311 stop.store(true, Ordering::Relaxed);
312 for w in workers {
313 w.join().unwrap();
314 }
315 walls.sort();
316 let missed = walls.iter().filter(|w| **w > period).count();
317 println!(
318 "workers at nice {nice}: frame work p50 {:.1} ms, p95 {:.1} ms, max {:.1} ms, {missed}/120 over 16.7 ms",
319 ms(walls[60]),
320 ms(walls[114]),
321 ms(walls[119])
322 );
323 }
324}
325
326/// Hot-path bookkeeping the optimisations removed allocations from: resident-set
327/// fingerprint (was a Vec build per placement call, twice per frame), LOD alpha
328/// with a caller-supplied resident test (was a HashSet build per record), and
329/// in-place centre-first sort (was a copy per frame). Host timings only.
330#[test]
331#[ignore = "timing harness; run with --ignored --nocapture"]
332fn per_frame_bookkeeping() {
333 use map_renderer::tile::select::{
334 sort_center_first, tile_lod_alpha, tile_lod_alpha_with, tiles_fingerprint,
335 };
336 use std::collections::HashSet;
337 // Synthetic resident set: 64 tiles (the resident cap) at z14 around SF.
338 let tiles: Vec<select::TileId> = (0..8)
339 .flat_map(|dy| (0..8).map(move |dx| select::TileId { z: 14, x: 2620 + dx, y: 6330 + dy }))
340 .collect();
341 let resident: HashSet<u64> = tiles.iter().map(|t| t.key()).collect();
342 let frames = 5_000;
343 let t = Instant::now();
344 let mut acc = 0u64;
345 for _ in 0..frames {
346 acc ^= tiles_fingerprint(tiles.iter().map(|t| (t.key(), 12345u32)));
347 }
348 println!("fingerprint 64 tiles: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);
349 std::hint::black_box(acc);
350 let t = Instant::now();
351 let mut a = 0f32;
352 for _ in 0..frames {
353 for tile in &tiles {
354 a += tile_lod_alpha(tile.key(), 0.0, 1.0, select::LOD_FADE_SECONDS, &resident);
355 }
356 }
357 println!("lod_alpha via HashSet: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);
358 let t = Instant::now();
359 let mut b = 0f32;
360 for _ in 0..frames {
361 for tile in &tiles {
362 b += tile_lod_alpha_with(tile.key(), 0.0, 1.0, select::LOD_FADE_SECONDS, |k| {
363 resident.contains(&k)
364 });
365 }
366 }
367 println!("lod_alpha via lookup: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);
368 assert_eq!(a, b);
369 let mut sorted = tiles.clone();
370 let t = Instant::now();
371 for _ in 0..frames {
372 sorted.clone_from(&tiles);
373 sort_center_first(&mut sorted);
374 }
375 println!("centre-first sort in place: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);
376 std::hint::black_box(sorted);
377}