Files
ecs/ecs/schedule.sakura
T
2026-11-14 15:37:58 -06:00

94 lines
2.6 KiB
Plaintext

#! Contains `schedule`: systems, the functions a program runs over its world,
#! in order, timing each.
import std::time;
module malunal::ecs;
# A system of a schedule, and how long it took.
struct step : owning {
var name: string;
var run: function<def(&mut world): void>;
var last: i64; # Nanoseconds.
var total: i64;
var runs: u64;
}
pub def step::close(&mut this): void {
this.name.close();
this.run.close();
}
#! Systems, each a function over a world, which `run` calls in the order they
#! were added, timing each, so a program sees what each costs.
pub struct schedule : owning {
var steps: vector<step>;
}
pub def schedule::new(): schedule {
return schedule{ steps = vector::<step>::new() };
}
#! How many systems it runs.
pub val schedule::length: u64 {
get => this.steps.length;
}
#! Adds a system, run after those added before it: a function of the world,
#! or a type of one's own with an `invoke` taking the world, which then holds
#! what the system keeps between runs, as its queries.
pub def schedule::add<F>(&mut this, name: strview, system: F): void where F: invokable<def(&mut world): void> {
this.steps.append(step{
name = string::from(name, nothing{}),
run = function::<def(&mut world): void>::new(move(system)),
});
}
#! Takes out the systems of a name, as a program stops what it added.
#! @returns Whether it ran any.
pub def schedule::remove(&mut this, name: strview): bool {
var found := false;
var i := 0u;
while i < this.steps.length {
if this.steps[i].name.span == name {
this.steps.remove_at(i);
found = true;
} else {
i++;
}
}
return found;
}
#! Runs every system over a world, in order.
pub def schedule::run(&mut this, w: &mut world): void {
for i in 0..this.steps.length {
val each := &mut this.steps[i];
val started := instant::now();
each.run(w);
each.last = started.elapsed().in_nanoseconds;
each.total += each.last;
each.runs++;
}
}
#! How long each system took as it last ran, and on average, in
#! milliseconds, a line for each, as `movement: 0.412 ms, 0.398 on average`.
pub def schedule::timings(&this): string {
var text := string::from("", nothing{});
for i in 0..this.steps.length {
val each := &this.steps[i];
val average := each.runs == 0 ? 0.0 : each.total as f64 / each.runs as f64;
text.append($"{each.name}: {milliseconds(each.last as f64)} ms, {milliseconds(average)} on average\n");
}
return text;
}
# Nanoseconds as milliseconds, to three places.
def milliseconds(ns: f64): f64 {
return (ns / 1000 + 0.5) as i64 as f64 / 1000;
}
pub def schedule::close(&mut this): void {
this.steps.close();
}