Sim::step phase timing and the CPU-profile bench driver (#147 step 3.1)
Mod side: Sim::step times plan_step, adapt, step_drones, step_moves, update_sight, step_sams and record, plus the whole step and its untimed remainder, through sim::profile. The simulation stays SDK-independent (also built as airdef-core): the adapter installs the host monotonic clock (game.monotonic-nanos) in init, native tests use std::time::Instant. The counters are fixed-size, per-thread, read no randomness and change no decision; /airdef stats reports them as PROFILE chat lines, reset per world. Driver: raid_bench gains --scheduler in-frame|server-thread (the two single-player paths, measured separately), HORIZON_MOD_CPU_PROFILE=1, the per-tick mod-path spans joined to the frame trace (per-frame totals, >25/33 ms counts, what the worst CPU frames carry), and the mod phase profile read at idle and battle end with the battle delta. report.json carries mod_cpu, mod_cpu_ticks, mod_phases_* and the derived correlation. Tests for the new helpers. Engine gitlink: mod-path CPU spans + game.monotonic-nanos (API level 32). Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
+28
-15
@@ -1229,6 +1229,8 @@ impl AirDef {
|
||||
let shader = self.sim.shader;
|
||||
let seed = game::get_clock().map_or(0x5eed, |c| c.game_time.wrapping_mul(2654435761) ^ 0x9e37);
|
||||
self.sim = Sim::new(seed);
|
||||
// A fresh world's CPU profile starts from zero (#147 step 3.1).
|
||||
sim::profile::reset();
|
||||
self.next_save = 0;
|
||||
self.sim.shader = shader;
|
||||
self.ground = Ground::default();
|
||||
@@ -1916,6 +1918,10 @@ fn help() -> String {
|
||||
|
||||
impl Mod for AirDef {
|
||||
fn init() -> Result<(Self, Registration), String> {
|
||||
// The CPU profile's clock (#147 step 3.1): the host's monotonic import.
|
||||
// Native tests keep the process clock (the import is a wasm-only stub).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
sim::profile::set_clock(game::monotonic_nanos);
|
||||
let seed = game::get_clock().map_or(0x5eed, |c| c.game_time.wrapping_mul(2654435761) ^ 0x9e37);
|
||||
let mut me = AirDef {
|
||||
sim: Sim::new(seed),
|
||||
@@ -2798,21 +2804,28 @@ impl Mod for AirDef {
|
||||
}
|
||||
None
|
||||
}
|
||||
["stats"] => Some(format!(
|
||||
"В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}",
|
||||
self.sim.drones.iter().filter(|d| d.alive()).count(),
|
||||
self.sim.missiles.len(),
|
||||
self.sim.sams.len(),
|
||||
self.sim.kills,
|
||||
self.sim.hits,
|
||||
self.sim.crashes,
|
||||
self.sim.strikes.fired,
|
||||
self.sim.strikes.destroyed,
|
||||
self.sim.strikes.stunned,
|
||||
self.sim.strikes.missed,
|
||||
self.sim.strikes.shot_down,
|
||||
world_view::text(&self.ground.world)
|
||||
)),
|
||||
["stats"] => {
|
||||
// The CPU profile's per-phase wall time (#147 step 3.1), as its
|
||||
// own chat lines so the bench can read them from the log.
|
||||
for l in sim::profile::report() {
|
||||
say(&l);
|
||||
}
|
||||
Some(format!(
|
||||
"В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}",
|
||||
self.sim.drones.iter().filter(|d| d.alive()).count(),
|
||||
self.sim.missiles.len(),
|
||||
self.sim.sams.len(),
|
||||
self.sim.kills,
|
||||
self.sim.hits,
|
||||
self.sim.crashes,
|
||||
self.sim.strikes.fired,
|
||||
self.sim.strikes.destroyed,
|
||||
self.sim.strikes.stunned,
|
||||
self.sim.strikes.missed,
|
||||
self.sim.strikes.shot_down,
|
||||
world_view::text(&self.ground.world)
|
||||
))
|
||||
}
|
||||
_ => return Err(help()),
|
||||
};
|
||||
self.emit(out);
|
||||
|
||||
@@ -41,6 +41,7 @@ pub mod outcome;
|
||||
mod units;
|
||||
pub mod why;
|
||||
pub mod world;
|
||||
pub mod profile;
|
||||
#[cfg(test)]
|
||||
mod balance;
|
||||
#[cfg(test)]
|
||||
@@ -1752,25 +1753,27 @@ impl Sim {
|
||||
});
|
||||
}
|
||||
|
||||
/// One game tick.
|
||||
/// One game tick. The named phases are timed for the CPU profile (#147 step
|
||||
/// 3.1); the timing reads no randomness and changes no decision.
|
||||
pub fn step(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||||
profile::begin_step();
|
||||
self.tick += 1;
|
||||
self.plan_step(Some(&mut *ground), out);
|
||||
self.adapt();
|
||||
profile::time(profile::PLAN, || self.plan_step(Some(&mut *ground), out));
|
||||
profile::time(profile::ADAPT, || self.adapt());
|
||||
self.step_refresh(out);
|
||||
self.step_settling(ground);
|
||||
self.release_queue(ground, out);
|
||||
self.begin_recording_if_active();
|
||||
self.step_drones(ground, player, out);
|
||||
profile::time(profile::DRONES, || self.step_drones(ground, player, out));
|
||||
self.step_recon(out);
|
||||
self.step_later(ground, player, out);
|
||||
self.step_moves(ground, out);
|
||||
profile::time(profile::MOVES, || self.step_moves(ground, out));
|
||||
self.step_supply(out);
|
||||
self.step_ew(out);
|
||||
self.update_sight(ground);
|
||||
profile::time(profile::SIGHT, || self.update_sight(ground));
|
||||
self.step_lights(ground, out);
|
||||
self.prepare_ground_strikes(out);
|
||||
self.step_sams(ground, out);
|
||||
profile::time(profile::SAMS, || self.step_sams(ground, out));
|
||||
self.step_missiles(ground, out);
|
||||
self.step_strikes(ground, player, out);
|
||||
self.step_fx(ground, out);
|
||||
@@ -1779,9 +1782,10 @@ impl Sim {
|
||||
self.step_wrecks(out);
|
||||
self.step_fires(ground, out);
|
||||
self.report_wave(out);
|
||||
self.record();
|
||||
profile::time(profile::RECORD, || self.record());
|
||||
let now = self.tick;
|
||||
self.blasts.retain(|b| now - b.start < b.life as u64);
|
||||
profile::end_step();
|
||||
}
|
||||
|
||||
// ------------------------------------------------ drones
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Per-phase wall time of `Sim::step` (#147 step 3.1): observation only, never
|
||||
//! a combat input. The simulation stays SDK-independent (it is also built as
|
||||
//! `airdef-core`), so the adapter installs the host clock
|
||||
//! (`game.monotonic-nanos`, API level 32) with [`set_clock`] before the first
|
||||
//! tick; native tests fall back to `std::time::Instant`. The counters are
|
||||
//! fixed-size and per-thread (a mod instance is single-threaded); timing reads
|
||||
//! no randomness and changes no decision, so the ordered combat trace is
|
||||
//! identical with or without it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// The named phases of `Sim::step`, as indices into the counters.
|
||||
pub const PLAN: usize = 0;
|
||||
pub const ADAPT: usize = 1;
|
||||
pub const DRONES: usize = 2;
|
||||
pub const MOVES: usize = 3;
|
||||
pub const SIGHT: usize = 4;
|
||||
pub const SAMS: usize = 5;
|
||||
pub const RECORD: usize = 6;
|
||||
const NAMED: usize = 7;
|
||||
/// The phases' report names, in index order.
|
||||
const NAMES: [&str; NAMED] = ["plan", "adapt", "drones", "moves", "sight", "sams", "record"];
|
||||
|
||||
#[derive(Default)]
|
||||
struct Prof {
|
||||
total_ns: [u64; NAMED],
|
||||
max_ns: [u64; NAMED],
|
||||
steps: u64,
|
||||
step_ns: u64,
|
||||
step_max_ns: u64,
|
||||
other_ns: u64,
|
||||
other_max_ns: u64,
|
||||
cur_start: u64,
|
||||
cur_named: u64,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PROF: RefCell<Prof> = const { RefCell::new(Prof {
|
||||
total_ns: [0; NAMED],
|
||||
max_ns: [0; NAMED],
|
||||
steps: 0,
|
||||
step_ns: 0,
|
||||
step_max_ns: 0,
|
||||
other_ns: 0,
|
||||
other_max_ns: 0,
|
||||
cur_start: 0,
|
||||
cur_named: 0,
|
||||
}) };
|
||||
}
|
||||
|
||||
/// The clock the adapter installs (the host's monotonic import); none in native
|
||||
/// tests, which use the process clock below.
|
||||
static CLOCK: std::sync::OnceLock<fn() -> u64> = std::sync::OnceLock::new();
|
||||
|
||||
/// Installs the monotonic clock, once, before the first timed step.
|
||||
pub fn set_clock(f: fn() -> u64) {
|
||||
let _ = CLOCK.set(f);
|
||||
}
|
||||
|
||||
fn now_ns() -> u64 {
|
||||
match CLOCK.get() {
|
||||
Some(f) => f(),
|
||||
None => native_now_ns(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn native_now_ns() -> u64 {
|
||||
use std::time::Instant;
|
||||
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
|
||||
EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64
|
||||
}
|
||||
|
||||
/// Only reached if the adapter never installed a clock; the mod always does in
|
||||
/// `init`, so the counters stay zero rather than reading an unsupported clock.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn native_now_ns() -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// Marks the start of one `Sim::step`.
|
||||
pub fn begin_step() {
|
||||
let start = now_ns();
|
||||
PROF.with(|p| {
|
||||
let p = &mut *p.borrow_mut();
|
||||
p.cur_start = start;
|
||||
p.cur_named = 0;
|
||||
});
|
||||
}
|
||||
|
||||
/// Times one named phase: its wall time joins the phase's counters and the
|
||||
/// step's named sum, so `end_step` can derive the untimed remainder.
|
||||
pub fn time<T>(phase: usize, f: impl FnOnce() -> T) -> T {
|
||||
let start = now_ns();
|
||||
let out = f();
|
||||
let dt = now_ns().saturating_sub(start);
|
||||
PROF.with(|p| {
|
||||
let p = &mut *p.borrow_mut();
|
||||
p.total_ns[phase] += dt;
|
||||
p.max_ns[phase] = p.max_ns[phase].max(dt);
|
||||
p.cur_named += dt;
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Marks the end of one `Sim::step`: the whole step and its untimed remainder.
|
||||
pub fn end_step() {
|
||||
let end = now_ns();
|
||||
PROF.with(|p| {
|
||||
let p = &mut *p.borrow_mut();
|
||||
let total = end.saturating_sub(p.cur_start);
|
||||
let other = total.saturating_sub(p.cur_named);
|
||||
p.steps += 1;
|
||||
p.step_ns += total;
|
||||
p.step_max_ns = p.step_max_ns.max(total);
|
||||
p.other_ns += other;
|
||||
p.other_max_ns = p.other_max_ns.max(other);
|
||||
});
|
||||
}
|
||||
|
||||
/// Clears the counters (a new world opens).
|
||||
pub fn reset() {
|
||||
PROF.with(|p| *p.borrow_mut() = Prof::default());
|
||||
}
|
||||
|
||||
/// Parseable chat lines for `/airdef stats`: each `PROFILE key=value ...` with
|
||||
/// millisecond totals and per-step maxima (three decimals) and the step count.
|
||||
/// `other` is the whole step minus the named phases. Split to stay under the
|
||||
/// game's 256-character chat line; the bench merges every `PROFILE` line.
|
||||
pub fn report() -> Vec<String> {
|
||||
PROF.with(|p| {
|
||||
let p = p.borrow();
|
||||
let ms = |ns: u64| ns as f64 / 1e6;
|
||||
let phase = |i: usize| {
|
||||
format!(
|
||||
"{}_ms={:.3} {}_max_ms={:.3}",
|
||||
NAMES[i], ms(p.total_ns[i]), NAMES[i], ms(p.max_ns[i]),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
format!(
|
||||
"PROFILE steps={} step_ms={:.3} step_max_ms={:.3} other_ms={:.3} other_max_ms={:.3}",
|
||||
p.steps, ms(p.step_ns), ms(p.step_max_ns), ms(p.other_ns), ms(p.other_max_ns),
|
||||
),
|
||||
format!("PROFILE {} {} {} {}", phase(0), phase(1), phase(2), phase(3)),
|
||||
format!("PROFILE {} {} {}", phase(4), phase(5), phase(6)),
|
||||
]
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user