garage44.eu/jeroen/frits

logclone: git clone https://garage44.eu/jeroen/frits.git

.. /crates/bench/src/main.rs

raw

//! Frits under the scenarios Cartopolis measured Luau and Bun with (session
//! s693, `tools/script-host/bench`, mac-1): N prims running one content pack,
//! 200 ticks at 20 Hz with a touch on prim 1 every 20 ticks; ten scripts that
//! never stop; load time; memory per script.
//!
//! The platform is a stand-in for the simulator's: prim state lives in Rust,
//! every call does the bookkeeping a host would (a command per change), and
//! channel messages are routed between prims after each tick.

use std::rc::Rc;
use std::time::Instant;

use frits::{Cx, HostValue, Limits, Platform, Runtime, Value};

const SIM: &str = "
type Geo = { lat: Float, lng: Float }
type Vec3 = { x: Float, y: Float, z: Float }
type Rgb = { r: Float, g: Float, b: Float }
type Particles = {
    count: Int, life: Float, speed: Float, spread_deg: Float, gravity: Float,
    source_radius: Float, size_start: Float, size_end: Float,
    color_start: Rgb, color_end: Rgb, turbulence: Float,
}

effect Prim {
    fn name(text: Str)
    fn color(c: Rgb)
    fn scale(s: Vec3)
    fn pos() -> Vec3
    fn set_pos(p: Vec3)
    fn geo() -> Geo
    fn set_geo(g: Geo)
    fn set_rot(degrees: Vec3)
    fn alpha(a: Float)
    fn glow(g: Float)
    fn physical(enabled: Bool)
    fn set_vel(v: Vec3)
    fn particles(p: Particles)
    fn burst(p: Particles)
    let fire: Particles
}
effect Chat {
    fn say(text: Str)
    fn shout(text: Str)
}
effect Channel {
    fn listen(channel: Int)
    fn send(channel: Int, text: Str)
}
effect Sensor {
    fn nearest(radius: Float) -> Option<{ distance: Float, id: Int, name: Str }>
}
effect Timer {
    fn every(seconds: Float)
    fn now() -> Float
}
effect Sound {
    fn play(name: Str)
}
module geo {
    fn metres_per_degree(lat: Float) -> Geo
}

event start()
event timer()
event message(channel: Int, text: Str, sender: Int)
event touch(id: Int, name: Str)
";

/// What the simulator would have to do with a script's call.
#[allow(dead_code)]
enum Command {
    Moved,
    Look,
    Particles,
    Said(String),
    Sound(String),
}

#[derive(Default)]
struct Prim {
    geo: (f64, f64),
    pos: [f64; 3],
    now: f64,
    timer: Option<f64>,
    next_timer: f64,
    listening: Vec<i64>,
    sent: Vec<(i64, String)>,
    commands: Vec<Command>,
    /// The avatar the sensor sees, if any: id, name, metres away.
    nearby: Option<(i64, String, f64)>,
}

fn vec3(cx: &Cx<Prim>, v: Value) -> [f64; 3] {
    let f = cx.fields(v);
    [f[0].float(), f[1].float(), f[2].float()]
}

fn platform() -> Platform<Prim> {
    let mut p = Platform::new(SIM).expect("the simulator declaration parses");
    fn look(cx: &mut Cx<Prim>, _: &[Value]) -> Result<Value, String> {
        cx.state.commands.push(Command::Look);
        Ok(Value::Unit)
    }
    fn particles(cx: &mut Cx<Prim>, a: &[Value]) -> Result<Value, String> {
        // A host reads the whole record to build its emitter.
        let n = cx.fields(a[0]).len();
        if n != 11 {
            return Err("bad particles".into());
        }
        cx.state.commands.push(Command::Particles);
        Ok(Value::Unit)
    }
    p.bind("Prim.name", look)
        .bind("Prim.color", look)
        .bind("Prim.scale", look)
        .bind("Prim.alpha", look)
        .bind("Prim.glow", look)
        .bind("Prim.physical", look)
        .bind("Prim.set_rot", look)
        .bind("Prim.set_vel", look)
        .bind("Prim.particles", particles)
        .bind("Prim.burst", particles)
        .bind("Prim.pos", |cx, _| {
            let [x, y, z] = cx.state.pos;
            Ok(cx.record(&[Value::Float(x), Value::Float(y), Value::Float(z)]))
        })
        .bind("Prim.set_pos", |cx, a| {
            cx.state.pos = vec3(cx, a[0]);
            cx.state.commands.push(Command::Moved);
            Ok(Value::Unit)
        })
        .bind("Prim.geo", |cx, _| {
            let (lat, lng) = cx.state.geo;
            Ok(cx.record(&[Value::Float(lat), Value::Float(lng)]))
        })
        .bind("Prim.set_geo", |cx, a| {
            let f = cx.fields(a[0]);
            cx.state.geo = (f[0].float(), f[1].float());
            cx.state.commands.push(Command::Moved);
            Ok(Value::Unit)
        })
        .bind("Chat.say", |cx, a| {
            let s = cx.str(a[0]).to_string();
            cx.state.commands.push(Command::Said(s));
            Ok(Value::Unit)
        })
        .bind("Chat.shout", |cx, a| {
            let s = cx.str(a[0]).to_string();
            cx.state.commands.push(Command::Said(s));
            Ok(Value::Unit)
        })
        .bind("Channel.listen", |cx, a| {
            cx.state.listening.push(a[0].int());
            Ok(Value::Unit)
        })
        .bind("Channel.send", |cx, a| {
            let s = cx.str(a[1]).to_string();
            cx.state.sent.push((a[0].int(), s));
            Ok(Value::Unit)
        })
        // No avatars in the benchmark world, as in s693's; the tests place one.
        .bind("Sensor.nearest", |cx, a| match cx.state.nearby.clone() {
            Some((id, name, d)) if d <= a[0].float() => {
                let name = cx.new_str(&name);
                let r = cx.record(&[Value::Float(d), Value::Int(id), name]);
                Ok(cx.some(r))
            }
            _ => Ok(cx.none()),
        })
        .bind("Timer.every", |cx, a| {
            cx.state.timer = Some(a[0].float());
            cx.state.next_timer = cx.state.now + a[0].float();
            Ok(Value::Unit)
        })
        .bind("Timer.now", |cx, _| Ok(Value::Float(cx.state.now)))
        .bind("Sound.play", |cx, a| {
            let s = cx.str(a[0]).to_string();
            cx.state.commands.push(Command::Sound(s));
            Ok(Value::Unit)
        })
        .bind("geo.metres_per_degree", |cx, a| {
            let phi = a[0].float().to_radians();
            let lat = 111_132.92 - 559.82 * (2.0 * phi).cos() + 1.175 * (4.0 * phi).cos();
            let lng = 111_412.84 * phi.cos() - 93.5 * (3.0 * phi).cos();
            Ok(cx.record(&[Value::Float(lat), Value::Float(lng)]))
        });
    let rgb = |r, g, b| {
        HostValue::Record(vec![
            HostValue::Float(b),
            HostValue::Float(g),
            HostValue::Float(r),
        ])
    };
    // Fields in name order: color_end, color_start, count, gravity, life,
    // size_end, size_start, source_radius, speed, spread_deg, turbulence.
    p.constant(
        "Prim.fire",
        HostValue::Record(vec![
            rgb(1.0, 0.1, 0.0),
            rgb(4.0, 1.5, 0.3),
            HostValue::Int(80),
            HostValue::Float(2.0),
            HostValue::Float(1.0),
            HostValue::Float(0.1),
            HostValue::Float(1.0),
            HostValue::Float(0.5),
            HostValue::Float(2.0),
            HostValue::Float(20.0),
            HostValue::Float(1.0),
        ]),
    );
    let unbound = p.unbound();
    assert!(unbound.is_empty(), "unbound: {unbound:?}");
    p
}

fn rss() -> f64 {
    let out = std::process::Command::new("ps")
        .args(["-o", "rss=", "-p", &std::process::id().to_string()])
        .output()
        .expect("ps");
    String::from_utf8_lossy(&out.stdout)
        .trim()
        .parse::<f64>()
        .unwrap_or(0.0)
        * 1024.0
}

fn stats(mut ms: Vec<f64>) -> (f64, f64) {
    ms.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let mean = ms.iter().sum::<f64>() / ms.len() as f64;
    let p99 = ms[((ms.len() as f64) * 0.99) as usize - 1];
    (mean, p99)
}

struct World {
    rt: Runtime<Prim>,
    pids: Vec<u32>,
    now: f64,
}

impl World {
    fn new() -> Self {
        World {
            rt: Runtime::new(platform()),
            pids: Vec::new(),
            now: 0.0,
        }
    }

    /// Compile each script on its own, as a host that stores source per prim must.
    fn load(&mut self, sources: &[&str], n: usize) -> f64 {
        let t = Instant::now();
        for i in 0..n {
            let m = self
                .rt
                .platform
                .compile(sources[i % sources.len()])
                .unwrap_or_else(|e| panic!("{e:?}"));
            let prim = Prim {
                geo: (53.2194, 6.5665),
                pos: [0.0, 0.0, 0.0],
                ..Default::default()
            };
            let pid = self.rt.spawn(m, prim);
            self.rt.post(pid, "start", Vec::new());
            self.pids.push(pid);
        }
        // Run the globals and `on start` before timing anything else.
        while !self.rt.tick().is_empty() {}
        t.elapsed().as_secs_f64() * 1000.0
    }

    /// One simulator tick: advance the clock, fire due timers, run a slice each,
    /// route channel messages. Returns milliseconds.
    fn tick(&mut self, dt: f64, touch: bool) -> f64 {
        let t = Instant::now();
        self.now += dt;
        let now = self.now;
        for (i, &pid) in self.pids.iter().enumerate() {
            let p = self.rt.get_mut(pid).unwrap();
            p.state.now = now;
            p.state.commands.clear();
            if let Some(every) = p.state.timer
                && now + 1e-9 >= p.state.next_timer
            {
                p.state.next_timer += every;
                p.post("timer", Vec::new());
            }
            if touch && i == 0 {
                p.post("touch", vec![HostValue::Int(42), HostValue::Str("Anna".into())]);
            }
        }
        let died = self.rt.tick();
        assert!(died.is_empty(), "{died:?}");
        // Deliver what was sent to everyone listening on the channel.
        let mut mail = Vec::new();
        for &pid in &self.pids {
            let p = self.rt.get_mut(pid).unwrap();
            for (ch, text) in p.state.sent.drain(..) {
                mail.push((pid, ch, text));
            }
        }
        if !mail.is_empty() {
            let listeners: Vec<(u32, Vec<i64>)> = self
                .pids
                .iter()
                .map(|&p| (p, self.rt.get(p).unwrap().state.listening.clone()))
                .collect();
            for (from, ch, text) in mail {
                for (to, chans) in &listeners {
                    if *to != from && chans.contains(&ch) {
                        let args = vec![
                            HostValue::Int(ch),
                            HostValue::Str(text.clone()),
                            HostValue::Int(from as i64),
                        ];
                        self.rt.post(*to, "message", args);
                    }
                }
            }
        }
        t.elapsed().as_secs_f64() * 1000.0
    }

    fn script_bytes(&self) -> usize {
        self.pids.iter().map(|&p| self.rt.get(p).unwrap().memory()).sum()
    }
}

fn main() {
    let firebird = include_str!("../scripts/firebird.frits");
    let football = include_str!("../scripts/football.frits");
    let idle = "script / Chat\non touch(id: Int, name: Str) { }";
    let groups: [(&str, Vec<&str>); 3] = [
        ("idle", vec![idle]),
        ("firebird", vec![firebird]),
        ("football", vec![football]),
    ];

    println!(
        "scenario  scripts  load_ms  tick_mean_ms  tick_p99_ms  rss_bytes_per_script  own_bytes_per_script"
    );
    for n in [200usize, 2000] {
        for (label, sources) in &groups {
            let before = rss();
            let mut w = World::new();
            let load_ms = w.load(sources, n);
            let mut ms = Vec::new();
            for tick in 0..200 {
                ms.push(w.tick(0.05, tick % 20 == 5));
            }
            let after = rss();
            let (mean, p99) = stats(ms);
            println!(
                "{label:<9} {n:>7}  {load_ms:>7.1}  {mean:>12.3}  {p99:>11.3}  {:>20.0}  {:>20.0}",
                (after - before) / n as f64,
                w.script_bytes() as f64 / n as f64
            );
        }
    }

    // Ten scripts that never stop, so every slice is spent: the fuel bank.
    let busy = "script / Chat\nvar s = 0\non start() { while true { s = s + 1\n if s % 100000 == 0 { Chat.say(\"{s}\") } } }";
    let calls = "script / Chat\nvar n = 0\nfn fib(k: Int) -> Int { if k < 2 { k } else { fib(k - 1) + fib(k - 2) } }\non start() { while true { let x = fib(15)\n n = n + 1\n if n % 100 == 0 { Chat.say(\"{n}\") } } }";
    println!();
    println!(
        "scenario  scripts  fuel_per_slice  tick_mean_ms  tick_p99_ms  instructions_per_tick  ns_per_instruction"
    );
    for (label, src) in [("busy", busy), ("calls", calls)] {
        let mut w = World::new();
        w.rt.limits = Limits::default();
        let m: Rc<_> = w.rt.platform.compile(src).unwrap();
        for _ in 0..10 {
            let pid = w.rt.spawn(m.clone(), Prim::default());
            w.rt.post(pid, "start", Vec::new());
            w.pids.push(pid);
        }
        let mut ms = Vec::new();
        for _ in 0..100 {
            ms.push(w.tick(0.05, false));
        }
        let (mean, p99) = stats(ms);
        let executed: u64 = w.pids.iter().map(|&p| w.rt.get(p).unwrap().executed).sum();
        let per_tick = executed as f64 / 100.0;
        let ns = mean * 1e6 / per_tick;
        println!(
            "{label:<9} {:>7}  {:>14}  {mean:>12.3}  {p99:>11.3}  {per_tick:>21.0}  {ns:>18.2}",
            10, w.rt.limits.fuel
        );
    }

    // One fib(15), measured alone with all the fuel it wants.
    let mut w = World::new();
    w.rt.limits.fuel = u64::MAX;
    let m = w.rt.platform.compile("script / Chat\nfn fib(k: Int) -> Int { if k < 2 { k } else { fib(k - 1) + fib(k - 2) } }\non start() { var i = 0\n while i < 1000 { let x = fib(15)\n i += 1 } }").unwrap();
    let pid = w.rt.spawn(m, Prim::default());
    w.rt.tick();
    w.rt.post(pid, "start", Vec::new());
    let t = Instant::now();
    w.rt.tick();
    let per = t.elapsed().as_secs_f64() * 1000.0 / 1000.0;
    println!(
        "\nfib(15): {per:.4} ms each ({} instructions each)",
        w.rt.get(pid).unwrap().executed / 1000
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    fn said(w: &World, pid: u32) -> Vec<String> {
        let p = w.rt.get(pid).unwrap();
        p.state
            .commands
            .iter()
            .filter_map(|c| {
                if let Command::Said(s) = c {
                    Some(s.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    #[test]
    fn the_firebird_circles_is_startled_explodes_and_reforms() {
        let mut w = World::new();
        w.load(&[include_str!("../scripts/firebird.frits")], 1);
        let pid = w.pids[0];
        let start = w.rt.get(pid).unwrap().state.geo;
        let mut heard = Vec::new();
        for _ in 0..20 {
            w.tick(0.05, false);
            heard.extend(said(&w, pid));
        }
        assert!(heard.is_empty(), "{heard:?}");
        assert_ne!(w.rt.get(pid).unwrap().state.geo, start, "it does not fly");
        // Someone walks up after the release grace has passed.
        while w.now < 6.0 {
            w.tick(0.05, false);
        }
        w.rt.get_mut(pid).unwrap().state.nearby = Some((7, "Anna".into(), 12.4));
        for _ in 0..120 {
            w.tick(0.05, false);
            heard.extend(said(&w, pid));
        }
        assert_eq!(heard, ["Anna is 12 m away. Stand back.", "..."]);
        assert_eq!(w.rt.get(pid).unwrap().state.sent.len(), 0);
    }

    #[test]
    fn the_beacon_summons_and_releases_it() {
        let mut w = World::new();
        w.load(&[include_str!("../scripts/firebird.frits")], 1);
        let pid = w.pids[0];
        let press = |w: &mut World| {
            w.rt.get_mut(pid).unwrap().state.commands.clear();
            w.rt.post(
                pid,
                "message",
                vec![
                    HostValue::Int(4747),
                    HostValue::Str("press".into()),
                    HostValue::Int(99),
                ],
            );
            // The runtime's tick, not the world's, which would deliver what it sent.
            assert!(w.rt.tick().is_empty());
            let p = w.rt.get_mut(pid).unwrap();
            let sent: Vec<String> = p.state.sent.drain(..).map(|(_, t)| t).collect();
            (said(w, pid), sent)
        };
        assert_eq!(
            press(&mut w),
            (vec!["Coming.".to_string()], vec!["here".to_string()])
        );
        assert_eq!(
            press(&mut w),
            (
                vec!["Back to the rounds.".to_string()],
                vec!["patrolling".to_string()]
            )
        );
    }

    #[test]
    fn the_football_counts_a_goal_and_restarts() {
        let mut w = World::new();
        w.load(&[include_str!("../scripts/football.frits")], 1);
        let pid = w.pids[0];
        // Just over the north goal line, between the posts, on the ground.
        w.rt.get_mut(pid).unwrap().state.geo = (53.20661975 + 0.00001, 6.5916658);
        let mut heard = Vec::new();
        for _ in 0..80 {
            w.tick(0.05, false);
            heard.extend(said(&w, pid));
        }
        assert_eq!(heard[0], "GOAL at the north end! North 0 – 1 South");
        let (lat, _) = w.rt.get(pid).unwrap().state.geo;
        assert!(
            (lat - 53.20614145).abs() < 1e-6,
            "not back on the centre spot: {lat}"
        );
        w.tick(0.05, true);
        assert_eq!(
            said(&w, pid),
            ["Anna puts the ball on the centre spot. North 0 – 1 South"]
        );
    }

    #[test]
    fn the_ported_scripts_are_formatted() {
        for src in [
            include_str!("../scripts/firebird.frits"),
            include_str!("../scripts/football.frits"),
        ] {
            assert_eq!(
                frits::fmt::format(src),
                src,
                "run `frits fmt crates/bench/scripts/*.frits`"
            );
        }
    }

    /// The `frits` examples in the documentation compile against this platform.
    #[test]
    fn the_documented_examples_compile() {
        let docs = [
            include_str!("../../../README.md"),
            include_str!("../../../docs/design.md"),
        ];
        let mut n = 0;
        for doc in docs {
            for block in doc.split("```frits\n").skip(1) {
                let src = block.split("```").next().unwrap();
                if let Err(e) = platform().compile(src) {
                    panic!("{e:?}\n{src}");
                }
                n += 1;
            }
        }
        assert_eq!(n, 3);
    }
}