### glassbench Macro Usage Source: https://docs.rs/glassbench/latest/glassbench/macro.glassbench.html Example of invoking the glassbench macro with a title and a list of benchmark functions. ```rust glassbench!( "Sortings", bench_number_sorting, bench_alpha_sorting, ); ``` -------------------------------- ### Bench::task usage example Source: https://docs.rs/glassbench/latest/glassbench/struct.Bench.html Example of defining a benchmark task using the task method. ```rust bench.task("answer 42", |task| { let computer = BigComputer::new(); let question = 42; task.iter(|| { pretend_used(computer.answer(question)); }); }); ``` -------------------------------- ### TaskBench::iter Source: https://docs.rs/glassbench/latest/glassbench/struct.TaskBench.html Calls the provided function to measure its execution time. Includes an initial warmup and runs the function enough times to get a reliable duration estimate. ```APIDOC ## TaskBench::iter ### Description Calls the provided function to measure its execution time. Includes an initial warmup and runs the function enough times to get a reliable duration estimate. ### Method iter ### Signature pub fn iter(&mut self, measured: M) where M: FnMut() -> R ### Parameters - **measured** (M) - Required - The closure to be measured. It must implement FnMut() -> R. ### Return Value No return value (unit type). ``` -------------------------------- ### Db::open Source: https://docs.rs/glassbench/latest/glassbench/struct.Db.html Creates a new instance of Db, creating the SQLite file and the tables if necessary. ```APIDOC ## Db::open ### Description Creates a new instance of Db, creating the SQLite file and the tables if necessary. ### Method open() ### Signature pub fn open() -> Result ### Returns - Result - A new Db instance or an error. ``` -------------------------------- ### TaskBench implementation methods Source: https://docs.rs/glassbench/latest/src/glassbench/task_bench.rs.html Provides methods for initializing a new TaskBench, calculating differences between benchmarks, and executing the measurement iteration logic. ```rust impl TaskBench { pub(crate) fn new(name: String) -> Self { Self { name, measure: None, } } pub(crate) fn diff_with(&self, old_bench: &Bench) -> Option { old_bench .tasks .iter() .find(|tb| tb.name == self.name) .and_then(|old_tb| old_tb.measure) .and_then(|old_mes| { self.measure .map(|new_mes| TaskBenchDiff::new(old_mes, new_mes)) }) } /// Call the function to measure /// /// There will be an initial warmup, after which /// the function will be called enought times to /// get a reliable estimation of its duration. pub fn iter(&mut self, mut measured: M) where M: FnMut() -> R, { if self.measure.is_some() { eprintln!("bench already used - please fix your benchmark"); return; } // just a warmup for _ in 0..WARMUP_ITERATIONS { measured(); } // first estimation, to compute the number of iterations later let start = Instant::now(); for _ in 0..ESTIMATE_ITERATIONS { measured(); } let estimate_ns = start.elapsed().as_nanos(); let iterations = ((OPTIMAL_DURATION_NS * ESTIMATE_ITERATIONS as u128) / estimate_ns) .try_into() .unwrap_or(MINIMAL_ITERATIONS) .max(MINIMAL_ITERATIONS); // now we do the real measure let start = Instant::now(); for _ in 0..iterations { measured(); } let total_duration = start.elapsed(); self.measure = Some(TaskMeasure { iterations, total_duration, }); } } ``` -------------------------------- ### Printer::new Source: https://docs.rs/glassbench/latest/glassbench/struct.Printer.html Creates a new Printer instance. The skin will be without style and color if the output is piped. ```APIDOC ## Printer::new ### Description Creates a new Printer instance. The skin will be without style and color if the output is piped. ### Method pub fn new() -> Self ### Parameters None ### Returns Self - A new Printer instance. ``` -------------------------------- ### Bench::new Source: https://docs.rs/glassbench/latest/glassbench/struct.Bench.html Creates a new Bench instance with a specific name and title. This method is typically not used directly; the glassbench! macro is preferred. ```APIDOC ## Bench::new ### Description Creates a new Bench instance with a specific name and title. This method is typically not used directly; the glassbench! macro is preferred. ### Method new ### Signature pub fn new(name: S1, title: S2) -> Self where S1: Into, S2: Into ### Parameters - **name** (S1) - Required - The name of the benchmark. - **title** (S2) - Required - The title of the benchmark. ### Returns - **Self** - A new Bench instance. ``` -------------------------------- ### after_bench(bench: &mut Bench, cmd: &Command) -> Result<(), GlassBenchError> Source: https://docs.rs/glassbench/latest/glassbench/fn.after_bench.html Prints the tabular report for the executed benchmark and then graphs, lists history, or saves according to the command. Returns a Result indicating success or a GlassBenchError. ```APIDOC ## after_bench(bench: &mut Bench, cmd: &Command) -> Result<(), GlassBenchError> ### Description Prints the tabular report for the executed benchmark and then graphs, lists history, or saves according to the command. Unless you have special reasons, you should not use this function but the glassbench! function. ### Function Signature pub fn after_bench( bench: &mut Bench, cmd: &Command, ) -> Result<(), GlassBenchError> ### Parameters - **bench** (&mut Bench) - Required - A mutable reference to the Bench object representing the executed benchmark. - **cmd** (&Command) - Required - A reference to the Command object that determines whether to graph, list history, or save. ### Return Value - **Result<(), GlassBenchError>** - Returns Ok(()) on success, or an Err containing a GlassBenchError on failure. ### Usage Notes This function is intended for advanced use cases. For typical usage, prefer the glassbench! macro. ``` -------------------------------- ### Bench::new constructor Source: https://docs.rs/glassbench/latest/src/glassbench/bench.rs.html Creates a new benchmark instance. It is recommended to use the glassbench! macro instead of calling this directly. ```rust impl Bench { /// Create a benchmark with a specific name and title /// /// You normally create don't use this function but the `glassbench!` /// macro which will fetch the id in the name of the executed benchmark. pub fn new(name: S1, title: S2) -> Self where S1: Into, S2: Into, { Self { time: Utc::now(), name: name.into(), title: title.into(), tasks: Vec::new(), tag: None, git_info: GitInfo::read(), } } ``` -------------------------------- ### create_bench Source: https://docs.rs/glassbench/latest/glassbench/fn.create_bench.html Creates a Bench with a user-defined name and command. This function is intended for special cases; the glassbench! macro is recommended for typical usage. ```APIDOC ## create_bench ### Description Creates a Bench with a user-defined name and command, instead of using the file name and command read from arguments. This function is provided for special cases; the glassbench! macro is recommended for normal usage. ### Signature pub fn create_bench(name: S1, title: S2, cmd: &Command) -> Bench where S1: Into, S2: Into, ### Parameters - **name** (S1) - Required - The user-defined name for the bench. - **title** (S2) - Required - The title for the bench. - **cmd** (&Command) - Required - The command to run for the bench. ### Returns - **Bench** - The created Bench instance. ### Notes Unless you have special reasons, you should not use this function but the glassbench! function. ``` -------------------------------- ### HtmlViewer::new Source: https://docs.rs/glassbench/latest/glassbench/struct.HtmlViewer.html Creates a new HtmlViewer instance with the given benchmark name and optional task name. ```APIDOC ## HtmlViewer::new ### Description Creates a new HtmlViewer instance with the given benchmark name and optional task name. ### Signature pub fn new(bench_name: &'b str, task_name: Option<&'b str>) -> Self ### Parameters - **bench_name** (&'b str) - Required - The name of the benchmark. - **task_name** (Option<&'b str>) - Optional - The name of the task, if any. ### Returns - **Self** - A new HtmlViewer instance. ``` -------------------------------- ### HTML Viewer Implementation Source: https://docs.rs/glassbench/latest/src/glassbench/html_viewer.rs.html The core implementation for building and writing the standalone HTML viewer, including resource embedding and configuration serialization. ```rust use { crate::*, serde::Serialize, std::{ fs::File, io::{self, Read}, path::PathBuf, }, }; pub const DOLL_JS: &str = include_str!("../rsc/dom-doll.js"); pub const VIS_JS: &str = include_str!("../rsc/vis-timeline-graph2d.min.js"); pub const VIS_CSS: &str = include_str!("../rsc/vis-timeline-graph2d.min.css"); pub const SQL_JS: &str = include_str!("../rsc/sql-wasm.js"); pub const SQL_WASM: &[u8] = include_bytes!("../rsc/sql-wasm.wasm"); pub const VIEWER_JS: &str = include_str!("../rsc/viewer.js"); pub const VIEWER_CSS: &str = include_str!("../rsc/viewer.css"); /// configuration sent to the html page in JSON #[derive(Debug, Serialize)] struct Conf<'b> { bench_name: &'b str, task_name: Option<&'b str>, gb_version: String, } /// The builder of the HTML standalone viewer pub struct HtmlViewer<'b> { conf: Conf<'b>, } impl<'b> HtmlViewer<'b> { pub fn new(bench_name: &'b str, task_name: Option<&'b str>) -> Self { Self { conf: Conf { bench_name, task_name, gb_version: env!("CARGO_PKG_VERSION").to_string(), }, } } pub fn open_in_browser(&self) -> Result<(), GlassBenchError> { let (mut w, path) = make_temp_file()?; self.write_html(&mut w)?; open::that(path)?; Ok(()) } pub fn write_html(&self, mut w: W) -> Result<(), GlassBenchError> { writeln!(w, "")?; writeln!(w, "")?; writeln!(w, "")?; writeln!(w, "")?; writeln!(w, "", VIEWER_CSS)?; writeln!(w, "", VIS_CSS)?; writeln!(w, "", VIS_JS)?; writeln!(w, "", SQL_JS)?; writeln!(w, "", DOLL_JS)?; writeln!(w, "", VIEWER_JS)?; write_db(&mut w)?; writeln!(w, "")?; writeln!(w, "")?; writeln!(w, "")?; writeln!(w, "")?; writeln!(w, "")?; Ok(()) } } pub fn make_temp_file() -> io::Result<(File, PathBuf)> { tempfile::Builder::new() .prefix("glassbench-") .suffix(".html") .rand_bytes(12) .tempfile()? .keep() .map_err(|_| io::Error::other("temp file can't be kept")) } pub fn write_db(mut w: W) -> Result<(), GlassBenchError> { let mut file = File::open(Db::path()?)?; let mut bytes = Vec::new(); file.read_to_end(&mut bytes)?; writeln!( w, r#""#, base64::encode(&bytes), )?; Ok(()) } ``` -------------------------------- ### Initialize Graph2d with vis.js Source: https://docs.rs/glassbench/latest/glassbench/constant.VIEWER_JS.html Initializes a vis.Graph2d instance with specific options and a click event listener. ```javascript (max_date-min_date)/10, shaded: true, } window.graph = new vis.Graph2d($("#vis"), items, groups, options) graph.on('click', function (properties) { console.log("click", properties) }) } ``` -------------------------------- ### create_bench function Source: https://docs.rs/glassbench/latest/src/glassbench/main_macro.rs.html Creates a new Bench instance with a custom name and title. It is recommended to use the glassbench! macro instead of calling this directly. ```rust pub fn create_bench(name: S1, title: S2, cmd: &Command) -> Bench where S1: Into, S2: Into, { let mut bench = Bench::new(name, title); bench.tag = cmd.tag.clone(); bench } ``` -------------------------------- ### Db::path Source: https://docs.rs/glassbench/latest/glassbench/struct.Db.html Returns the name of the glassbench database file. ```APIDOC ## Db::path ### Description Returns the name of the glassbench database file. ### Method path() ### Signature pub fn path() -> Result ### Returns - Result - The path to the database file or an error. ``` -------------------------------- ### Command::read Source: https://docs.rs/glassbench/latest/glassbench/struct.Command.html Reads the command-line arguments from std::env::args and returns a Command instance. ```APIDOC ## Command::read ### Description Reads the command-line arguments from std::env::args and returns a Command instance. ### Method read ### Signature pub fn read() -> Self ### Parameters None ### Returns - **Self** - A Command instance populated with the parsed arguments. ### Example ```rust let command = Command::read(); ``` ``` -------------------------------- ### Report::new Source: https://docs.rs/glassbench/latest/glassbench/struct.Report.html Creates a new Report instance with a reference to the benchmark and an optional previous benchmark for comparison. ```APIDOC ## Report::new ### Description Creates a new Report instance with a reference to the benchmark and an optional previous benchmark for comparison. ### Method new ### Signature pub fn new(bench: &'b Bench, previous: &'b Option) -> Self ### Parameters - **bench** (&'b Bench) - Required - The benchmark to report on. - **previous** (&'b Option) - Required - An optional previous benchmark for comparison. ### Returns - **Self** - A new Report instance. ``` -------------------------------- ### after_bench Source: https://docs.rs/glassbench/latest/glassbench/index.html Prints the tabular report for the executed benchmark then graph, list history, and or save according to command. ```APIDOC ## after_bench ### Description Prints the tabular report for the executed benchmark then graph, list history, and or save according to command. ### Usage Call this function after running a benchmark to output results. ### Parameters - **bench** (Bench) - Required - The benchmark that was executed. - **command** (Command) - Required - The command specifying what to do. ### Example ```rust after_bench(&bench, &command); ``` ``` -------------------------------- ### glassbench! macro Source: https://docs.rs/glassbench Generates a benchmark with a consistent id (using the benchmark file title), calling the benchmarking functions given in argument. ```APIDOC ## glassbench! macro ### Description Generates a benchmark with a consistent id (using the benchmark file title), calling the benchmarking functions given in argument. ### Usage Use the macro to define a benchmark with a title and task functions. ### Parameters - **benchmarking functions** (function) - Required - Functions that define tasks to benchmark. ### Example ```rust glassbench! { "My Benchmark", my_task, } ``` ``` -------------------------------- ### Initialize terminal skin with make_skin Source: https://docs.rs/glassbench/latest/src/glassbench/skin.rs.html The make_skin function acts as a factory to return a MadSkin instance, choosing between colored or no-color styles based on the provided boolean argument. ```rust 1use termimad::{ 2 crossterm::style::{Attribute::*, Color::*}, 3 minimad::Alignment, 4 MadSkin, 5}; 6 7/// crate the skin used for terminal display using Termimad 8pub fn make_skin(color: bool) -> MadSkin { 9 if color { 10 make_color_skin() 11 } else { 12 make_no_color_skin() 13 } 14} 15 16fn make_color_skin() -> MadSkin { 17 let mut skin = MadSkin::default(); 18 //skin.paragraph.set_fg(AnsiValue(153)); 19 skin.headers[0].align = Alignment::Left; 20 skin.set_headers_fg(AnsiValue(153)); 21 skin.strikeout.remove_attr(CrossedOut); 22 skin.strikeout.set_fg(AnsiValue(9)); 23 skin.italic.remove_attr(Italic); 24 skin.italic.set_fg(AnsiValue(70)); 25 skin 26} 27 28fn make_no_color_skin() -> MadSkin { 29 MadSkin::no_style() 30} ``` -------------------------------- ### TaskBench::iter Source: https://docs.rs/glassbench Runs the given callback repeatedly to measure its performance. This is the core method for benchmarking a specific operation. ```APIDOC ## TaskBench::iter ### Description Runs the given callback repeatedly to measure its performance. This is the core method for benchmarking a specific operation. ### Method function ### Parameters - **callback** (function) - Required - The closure to benchmark. ### Example ```rust task.iter(|| { // code to benchmark }); ``` ``` -------------------------------- ### Create UI Selectors Source: https://docs.rs/glassbench/latest/glassbench/constant.VIEWER_JS.html Generates dynamic UI elements for selecting benchmarks and tasks, including event handlers for updating views. ```javascript function make_selector(bench_name, task_name) { let bench_name_select = $(" $(`