1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
//! Molt Benchmark Harness
//!
//! A Molt benchmark script is a Molt script containing benchmarks of Molt code.  Each
//! benchmark is a call of the Molt `benchmark` command provided by the
//! `molt_shell::bench` module.  The benchmarks are executed in the context of the
//! the application's `molt::Interp` (and so can benchmark application-specific commands).
//!
//! The harness executes each benchmark many times and retains the average run-time
//! in microseconds. The `molt-app` tool provides access to the test harness for a
//! standard Molt interpreter.
//!
//! See the Molt Book (or the Molt benchmark suite) for how to write
//! benchmarks and examples of benchmark scripts.

use molt::check_args;
use molt::molt_ok;
use molt::ContextID;
use molt::Interp;
use molt::MoltInt;
use molt::MoltResult;
use molt::ResultCode;
use molt::Value;
use std::env;
use std::fs;
use std::path::PathBuf;

/// Executes the Molt benchmark harness, given the command-line arguments,
/// in the context of the given interpreter.
///
/// The first element of the `args` array must be the name of the benchmark script
/// to execute.  The remaining elements are benchmark options.  To see the list
/// of options, see The Molt Book or execute this function with an empty argument
/// list.
///
/// See [`molt::interp`](../molt/interp/index.html) for details on how to configure and
/// add commands to a Molt interpreter.
///
/// # Example
///
/// ```
/// use molt::Interp;
/// use std::env;
///
/// // FIRST, get the command line arguments.
/// let args: Vec<String> = env::args().collect();
///
/// // NEXT, create and initialize the interpreter.
/// let mut interp = Interp::new();
///
/// // NOTE: commands can be added to the interpreter here.
///
/// // NEXT, evaluate the file, if any.
/// if args.len() > 1 {
///     molt_shell::benchmark(&mut interp, &args[1..]);
/// } else {
///     eprintln!("Usage: mybench *filename.tcl");
/// }
/// ```
pub fn benchmark(interp: &mut Interp, args: &[String]) {
    // FIRST, get the script file name
    if args.is_empty() {
        eprintln!("Missing benchmark script.");
        write_usage();
        return;
    }

    // NEXT, parse any options.
    let mut output_csv = false;

    let mut iter = args[1..].iter();
    loop {
        let opt = iter.next();
        if opt.is_none() {
            break;
        }

        let opt = opt.unwrap();

        match opt.as_ref() {
            "-csv" => {
                output_csv = true;
            }
            _ => {
                eprintln!("Unknown option: \"{}\"", opt);
                write_usage();
                return;
            }
        }
    }

    // NEXT, get the parent folder from the path, if any.  We'll cd into the parent so
    // the `source` command can find scripts there.
    let path = PathBuf::from(&args[0]);
    let parent = path.parent();

    // NEXT, initialize the benchmark context.
    let context_id = interp.save_context(Context::new());

    // NEXT, install the test commands into the interpreter.
    interp.add_command("ident", cmd_ident);
    interp.add_context_command("measure", measure_cmd, context_id);
    interp.add_command("ok", cmd_ok);

    // NEXT, load the benchmark Tcl library
    if let Err(ResultCode::Error(value)) = interp.eval(include_str!("bench.tcl")) {
        panic!("Error in benchmark Tcl library: {}", value.as_str());
    }

    // NEXT, execute the script.
    match fs::read_to_string(&args[0]) {
        Ok(script) => {
            if parent.is_some() {
                let _ = env::set_current_dir(parent.unwrap());
            }
            match interp.eval(&script) {
                Ok(_) => (),
                Err(ResultCode::Error(msg)) => {
                    eprintln!("{}", msg);
                    std::process::exit(1);
                }
                Err(result) => {
                    eprintln!("Unexpected eval return: {:?}", result);
                    std::process::exit(1);
                }
            }
        }
        Err(e) => println!("{}", e),
    }

    // NEXT, output the test results:
    let ctx = interp.context::<Context>(context_id);

    if output_csv {
        write_csv(ctx);
    } else {
        write_formatted_text(ctx);
    }
}

fn write_csv(ctx: &Context) {
    println!("\"benchmark\",\"description\",\"nanos\",\"norm\"");

    let baseline = ctx.baseline();

    for record in &ctx.measurements {
        println!(
            "\"{}\",\"{}\",{},{}",
            strip_quotes(&record.name),
            strip_quotes(&record.description),
            record.nanos,
            record.nanos as f64 / (baseline as f64),
        );
    }
}

fn strip_quotes(string: &str) -> String {
    let out: String = string
        .chars()
        .map(|ch| if ch == '\"' { '\'' } else { ch })
        .collect();
    out
}

fn write_formatted_text(ctx: &Context) {
    write_version();
    println!();
    println!("{:>8} {:>8} -- Benchmark", "Micros", "Norm");

    let baseline = ctx.baseline();

    for record in &ctx.measurements {
        println!(
            "{:>8} {:>8.2} -- {} {}",
            record.nanos,
            record.nanos as f64 / (baseline as f64),
            record.name,
            record.description
        );
    }
}

fn write_version() {
    println!("Molt {} -- Benchmark", env!("CARGO_PKG_VERSION"));
}

fn write_usage() {
    write_version();
    println!();
    println!("Usage: molt bench filename.tcl [-csv]");
}

struct Context {
    // The baseline, in microseconds
    baseline: Option<MoltInt>,

    // The list of measurements.
    measurements: Vec<Measurement>,
}

impl Context {
    fn new() -> Self {
        Self {
            baseline: None,
            measurements: Vec::new(),
        }
    }

    fn baseline(&self) -> MoltInt {
        self.baseline.unwrap_or(1)
    }
}

struct Measurement {
    // The measurement's symbolic name
    name: String,

    // The measurement's human-readable description
    description: String,

    // The average number of nanoseconds per measured iteration
    nanos: MoltInt,
}

/// # measure *name* *description* *micros*
///
/// Records a benchmark measurement.
fn measure_cmd(interp: &mut Interp, context_id: ContextID, argv: &[Value]) -> MoltResult {
    molt::check_args(1, argv, 4, 4, "name description nanos")?;

    // FIRST, get the arguments
    let name = argv[1].to_string();
    let description = argv[2].to_string();
    let nanos = argv[3].as_int()?;

    // NEXT, get the test context
    let ctx = interp.context::<Context>(context_id);

    if ctx.baseline.is_none() {
        ctx.baseline = Some(nanos);
    }

    let record = Measurement {
        name,
        description,
        nanos,
    };

    ctx.measurements.push(record);

    molt_ok!()
}

/// # ident value
///
/// Returns its argument.
fn cmd_ident(_interp: &mut Interp, argv: &[Value]) -> MoltResult {
    check_args(1, argv, 2, 2, "value")?;

    molt_ok!(argv[1].clone())
}

/// # ok ...
///
/// Takes any number of arguments, and returns "".
fn cmd_ok(_interp: &mut Interp, _argv: &[Value]) -> MoltResult {
    molt_ok!()
}