Skip to main content

tasm_lib/
snippet_bencher.rs

1use serde::Deserialize;
2use serde::Serialize;
3use triton_vm::aet::AlgebraicExecutionTrace;
4use triton_vm::prelude::TableId;
5
6#[derive(Clone, Debug, Serialize, Deserialize)]
7pub struct BenchmarkResult {
8    pub clock_cycle_count: usize,
9    pub hash_table_height: usize,
10    pub u32_table_height: usize,
11    pub op_stack_table_height: usize,
12    pub ram_table_height: usize,
13}
14
15#[derive(Clone, Debug, Serialize, Deserialize)]
16pub struct NamedBenchmarkResult {
17    pub name: String,
18    pub benchmark_result: BenchmarkResult,
19    pub case: BenchmarkCase,
20}
21
22#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
23pub enum BenchmarkCase {
24    CommonCase,
25    WorstCase,
26}
27
28impl BenchmarkResult {
29    pub fn new(aet: &AlgebraicExecutionTrace) -> Self {
30        BenchmarkResult {
31            clock_cycle_count: aet.height_of_table(TableId::Processor),
32            hash_table_height: aet.height_of_table(TableId::Hash),
33            u32_table_height: aet.height_of_table(TableId::U32),
34            op_stack_table_height: aet.height_of_table(TableId::OpStack),
35            ram_table_height: aet.height_of_table(TableId::Ram),
36        }
37    }
38}
39
40#[cfg(not(target_arch = "wasm32"))]
41pub fn write_benchmarks(benchmarks: Vec<NamedBenchmarkResult>) {
42    if benchmarks.is_empty() {
43        return;
44    }
45
46    let mut path = std::path::PathBuf::new();
47    path.push("benchmarks");
48    std::fs::create_dir_all(&path).expect("benchmarks directory should exist");
49
50    let function_name = benchmarks[0].name.as_str();
51    assert!(
52        benchmarks.iter().all(|bench| bench.name == function_name),
53        "all fn names must agree for benchmark writing to disk",
54    );
55
56    path.push(std::path::Path::new(function_name).with_extension("json"));
57    let output = std::fs::File::create(&path).expect("open file for writing");
58    serde_json::to_writer_pretty(output, &benchmarks).expect("write json to file");
59}
60
61// file access is not possible on `wasm32` architectures; ignore attempts
62#[cfg(target_arch = "wasm32")]
63pub fn write_benchmarks(_: Vec<NamedBenchmarkResult>) {}