tasm_lib/
snippet_bencher.rs

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