Skip to main content

jit_loop/
jit_loop.rs

1//! Compare interpreter vs JIT on a tight counting loop (`feature = "jit"`).
2//!
3//! Built only with the public [`byteflow`] facade.
4//!
5//! ```text
6//! cargo run -p byteflow-actors --example jit_loop --features jit --release
7//! ```
8
9use std::time::Instant;
10
11use byteflow::{Chunk, FlowOutcome, Program, Runtime, RuntimeConfig, Value};
12
13#[cfg(feature = "jit")]
14use byteflow::JitConfig;
15
16fn loop_chunk(iterations: i32) -> Chunk {
17    let mut program = Program::new("jit-loop");
18    program.function("main", 0, |f| {
19        let limit = f.load_int(i64::from(iterations));
20        let counter = f.load_i32(0);
21        f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
22        f.return_(counter);
23    });
24    program.build()
25}
26
27fn runtime_config(jit: bool) -> RuntimeConfig {
28    #[cfg(feature = "jit")]
29    {
30        RuntimeConfig {
31            workers: 1,
32            quantum: 50_000_000,
33            jit: JitConfig {
34                enabled: jit,
35                hot_threshold: 1,
36            },
37            ..Default::default()
38        }
39    }
40    #[cfg(not(feature = "jit"))]
41    {
42        let _ = jit;
43        RuntimeConfig {
44            workers: 1,
45            quantum: 50_000_000,
46            ..Default::default()
47        }
48    }
49}
50
51fn run_once(jit: bool) -> Result<(), Box<dyn std::error::Error>> {
52    let chunk = loop_chunk(1_000_000);
53    let rt = Runtime::with_config(chunk, runtime_config(jit))?;
54    let start = Instant::now();
55    let outcome = rt.spawn(0, &[])?.join();
56    let snapshot = rt.metrics();
57    rt.shutdown();
58    let elapsed = start.elapsed();
59    match outcome {
60        FlowOutcome::Completed(Value::Int(n)) => {
61            println!("jit={jit} result={n} elapsed={elapsed:?} metrics={snapshot}");
62            Ok(())
63        }
64        other => Err(format!("unexpected outcome: {other:?}").into()),
65    }
66}
67
68fn main() {
69    println!("interpreter:");
70    if let Err(e) = run_once(false) {
71        eprintln!("{e}");
72        std::process::exit(1);
73    }
74    println!("jit:");
75    if let Err(e) = run_once(true) {
76        eprintln!("{e}");
77        std::process::exit(1);
78    }
79}