1#![allow(clippy::unwrap_used, clippy::expect_used, missing_docs, clippy::indexing_slicing, clippy::panic)]
7
8use std::time::Instant;
9
10use remedy_lua::{Libs, Limits, Lua};
11
12fn rss() -> usize {
13 std::fs::read_to_string("/proc/self/statm")
14 .ok()
15 .and_then(|s| s.split_whitespace().nth(1).and_then(|x| x.parse::<usize>().ok()))
16 .map_or(0, |p| p * 4096)
17}
18
19fn state(mem: usize, fast: bool) -> Lua {
20 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
21 let mut lua = Lua::new(Limits::default().memory(mem).string_len(32 << 20).fuel(1 << 34).hash_seed(7), libs);
22 lua.add_module("hostmod", "local M = {n = 1} for i = 1, 20 do M[i] = function() return i end end return M");
23 lua.set_fast_loop(fast);
24 lua.set_print(|_| {});
25 lua
26}
27
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}
42
43fn main() {
44 let a: Vec<String> = std::env::args().collect();
45 let text = |s: Option<&String>| match s {
47 Some(s) if s.starts_with('@') => std::fs::read_to_string(&s[1..]).unwrap(),
48 Some(s) => s.clone(),
49 None => String::new(),
50 };
51 let setup = text(a.get(1));
52 let body = text(a.get(2));
53 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
54 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(256) << 20;
55 let mut base = f64::MAX;
56 for _ in 0..3 {
57 base = base.min(run("", "local x = I * 2 local y = {} ", fuel, 64 << 20, true).0);
58 }
59 for fast in [true, false] {
60 let (c, used, r, mu, g) = run(&setup, &body, fuel, mem, fast);
61 println!(
62 "fast {fast}: {:.1}x plain ({c:.1} ns/unit vs {base:.1}), fuel {used}, mem_used {} KiB, rss gain {} KiB, {r}",
63 c / base,
64 mu >> 10,
65 g >> 10
66 );
67 }
68}