Skip to main content

frontmem/
frontmem.rs

1//! Front-end memory: peak resident memory (Linux `VmHWM`) of one load of a file against
2//! the memory limit it ran under. Each run is its own process, so the peak is the load's.
3//! `cargo run --release --example frontmem -p remedy-lua -- FILE LIMIT_BYTES [host|call|check]`
4#![allow(clippy::unwrap_used, missing_docs, clippy::print_stdout)]
5
6use remedy_lua::{Libs, Limits, Lua};
7
8fn hwm() -> usize {
9    let s = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
10    s.lines()
11        .find(|l| l.starts_with("VmHWM"))
12        .and_then(|l| l.split_whitespace().nth(1)?.parse::<usize>().ok())
13        .map_or(0, |kb| kb << 10)
14}
15
16fn main() {
17    let mut args = std::env::args().skip(1);
18    let file = args.next().unwrap();
19    let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20    let mode = args.next().unwrap_or_else(|| "host".into());
21    let src = std::fs::read(&file).unwrap();
22    let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23    let before = hwm();
24    let t = std::time::Instant::now();
25    let outcome = match mode.as_str() {
26        "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27        "call" => {
28            let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29            let s = lua.create_string(&src).unwrap();
30            lua.set_global("src", s).unwrap();
31            let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32            format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33        }
34        _ => {
35            let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36            format!("{:?}", lua.load(&src, name).map(|_| ()))
37        }
38    };
39    let peak = hwm();
40    println!(
41        "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42        t.elapsed(),
43        peak as f64 / 1e6,
44        before as f64 / 1e6,
45        limit as f64 / 1048576.0,
46        peak as f64 / limit as f64
47    );
48}