1#![allow(clippy::unwrap_used, clippy::expect_used, missing_docs, clippy::indexing_slicing, clippy::panic)]
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10
11use remedy_lua::{Libs, Limits, Lua};
12
13fn gap_clock() -> (remedy_lua::Clock, Arc<Mutex<(Instant, Duration, u64)>>) {
15 let st = Arc::new(Mutex::new((Instant::now(), Duration::ZERO, 0u64)));
16 let s = Arc::clone(&st);
17 let t0 = Instant::now();
18 let clock: remedy_lua::Clock = Arc::new(move || {
19 let now = Instant::now();
20 let mut g = s.lock().unwrap();
21 g.1 = g.1.max(now - g.0);
22 if std::env::var_os("GAPLOG").is_some() && now - g.0 > Duration::from_millis(1) {
23 eprintln!("gap {:?} at read {} t {:?}", now - g.0, g.2, now - t0);
24 }
25 g.0 = now;
26 g.2 += 1;
27 now - t0
28 });
29 (clock, st)
30}
31
32fn main() {
33 let a: Vec<String> = std::env::args().collect();
34 let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35 let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36 let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37 lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39 let (clock, st) = gap_clock();
40 lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41 let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42 let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43 st.lock().unwrap().0 = Instant::now();
44 let t = Instant::now();
45 lua.call(f.value(), &[]).unwrap();
46 let all = t.elapsed();
47 let g = *st.lock().unwrap();
48 println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49 println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50 let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51 println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52 println!(
53 "{:?}",
54 lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55 );
56 if k == 0 {
57 return;
58 }
59 let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62 let full = {
63 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64 let t = Instant::now();
65 l.load(&src, "=t").unwrap();
66 t.elapsed()
67 };
68 let mut worst = Duration::ZERO;
69 for p in 1..=12u32 {
70 let at = full * p / 13;
71 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72 let h = l.interrupt_handle();
73 let th = std::thread::spawn(move || {
74 std::thread::sleep(at);
75 h.interrupt();
76 Instant::now()
77 });
78 let r = l.load(&src, "=t").map(|_| ());
79 let end = Instant::now();
80 let fired = th.join().unwrap();
81 if r.is_err() {
82 worst = worst.max(end.saturating_duration_since(fired));
83 }
84 }
85 println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}