|
| 1 | +#![allow(clippy::as_conversions)] |
| 2 | + |
| 3 | +use std::fs::{self, File}; |
| 4 | +use std::time::Instant; |
| 5 | + |
| 6 | +use csv::Writer; |
| 7 | +use rand::rngs::StdRng; |
| 8 | +use rand::SeedableRng; |
| 9 | +use starknet_committer::block_committer::commit::commit_block; |
| 10 | +use starknet_committer::block_committer::input::{ConfigImpl, Input}; |
| 11 | +use starknet_committer::block_committer::state_diff_generator::generate_random_state_diff; |
| 12 | +use starknet_patricia::hash::hash_trait::HashOutput; |
| 13 | +use starknet_patricia_storage::map_storage::MapStorage; |
| 14 | +use tracing::info; |
| 15 | + |
| 16 | +pub type InputImpl = Input<ConfigImpl>; |
| 17 | +struct TimeMeasurement { |
| 18 | + timer: Option<Instant>, |
| 19 | + total_time: u128, // Total duration of all blocks (milliseconds). |
| 20 | + per_fact_durations: Vec<u64>, // Average duration (microseconds) per new fact in a block. |
| 21 | + n_facts: Vec<usize>, |
| 22 | + block_durations: Vec<u64>, // Duration of a block (milliseconds). |
| 23 | + facts_in_db: Vec<usize>, |
| 24 | + total_facts: usize, |
| 25 | +} |
| 26 | + |
| 27 | +impl TimeMeasurement { |
| 28 | + fn new(n_iterations: usize) -> Self { |
| 29 | + Self { |
| 30 | + timer: None, |
| 31 | + total_time: 0, |
| 32 | + per_fact_durations: Vec::with_capacity(n_iterations), |
| 33 | + n_facts: Vec::with_capacity(n_iterations), |
| 34 | + block_durations: Vec::with_capacity(n_iterations), |
| 35 | + facts_in_db: Vec::with_capacity(n_iterations), |
| 36 | + total_facts: 0, |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + fn start_measurement(&mut self) { |
| 41 | + self.timer = Some(Instant::now()); |
| 42 | + } |
| 43 | + |
| 44 | + fn stop_measurement(&mut self, facts_count: usize) { |
| 45 | + let duration = |
| 46 | + self.timer.expect("stop_measurement called before start_measurement").elapsed(); |
| 47 | + info!( |
| 48 | + "Time elapsed for iteration {}: {} milliseconds", |
| 49 | + self.n_results(), |
| 50 | + duration.as_millis() |
| 51 | + ); |
| 52 | + self.total_time += duration.as_millis(); |
| 53 | + self.per_fact_durations |
| 54 | + .push(duration.div_f32(facts_count as f32).as_micros().try_into().unwrap()); |
| 55 | + self.block_durations.push(duration.as_millis().try_into().unwrap()); |
| 56 | + self.n_facts.push(facts_count); |
| 57 | + self.facts_in_db.push(self.total_facts); |
| 58 | + self.total_facts += facts_count; |
| 59 | + } |
| 60 | + |
| 61 | + fn n_results(&self) -> usize { |
| 62 | + self.block_durations.len() |
| 63 | + } |
| 64 | + |
| 65 | + /// Returns the average time per block (milliseconds). |
| 66 | + fn block_average_time(&self) -> f64 { |
| 67 | + self.total_time as f64 / self.n_results() as f64 |
| 68 | + } |
| 69 | + |
| 70 | + /// Returns the average time per fact over a window of `window_size` blocks (microseconds). |
| 71 | + fn average_window_time(&self, window_size: usize) -> Vec<f64> { |
| 72 | + let mut averages = Vec::new(); // In milliseconds. |
| 73 | + // Takes only the full windows, so if the last window is smaller than `window_size`, it is |
| 74 | + // ignored. |
| 75 | + let n_windows = self.n_results() / window_size; |
| 76 | + for i in 0..n_windows { |
| 77 | + let window_start = i * window_size; |
| 78 | + let sum: u64 = |
| 79 | + self.block_durations[window_start..window_start + window_size].iter().sum(); |
| 80 | + let sum_of_facts: usize = |
| 81 | + self.n_facts[window_start..window_start + window_size].iter().sum(); |
| 82 | + averages.push(1000.0 * sum as f64 / sum_of_facts as f64); |
| 83 | + } |
| 84 | + averages |
| 85 | + } |
| 86 | + |
| 87 | + fn pretty_print(&self, window_size: usize) { |
| 88 | + if self.n_results() == 0 { |
| 89 | + println!("No measurements were taken."); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + println!( |
| 94 | + "Total time: {} milliseconds for {} iterations", |
| 95 | + self.total_time, |
| 96 | + self.n_results() |
| 97 | + ); |
| 98 | + println!("Average block time: {:.2} milliseconds", self.block_average_time()); |
| 99 | + |
| 100 | + println!("Average time per window of {window_size} iterations:"); |
| 101 | + let means = self.average_window_time(window_size); |
| 102 | + let max = means.iter().cloned().fold(f64::MIN, f64::max); |
| 103 | + // Print a graph visualization of block times. |
| 104 | + for (i, fact_duration) in means.iter().enumerate() { |
| 105 | + let norm = fact_duration / max; |
| 106 | + let width = (norm * 40.0).round() as usize; // up tp 40 characters wide |
| 107 | + let bar = "█".repeat(width.max(1)); |
| 108 | + println!("win {i:>4}: {fact_duration:>8.4} microsecond / fact | {bar}"); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + fn to_csv(&self, path: &str, output_dir: &str) { |
| 113 | + let _ = fs::create_dir_all(output_dir); |
| 114 | + let file = |
| 115 | + File::create(format!("{output_dir}/{path}")).expect("Failed to create CSV file."); |
| 116 | + let mut wtr = Writer::from_writer(file); |
| 117 | + wtr.write_record([ |
| 118 | + "block_number", |
| 119 | + "n_facts", |
| 120 | + "facts_in_db", |
| 121 | + "time_per_fact_micros", |
| 122 | + "block_duration_millis", |
| 123 | + ]) |
| 124 | + .expect("Failed to write CSV header."); |
| 125 | + for (i, (((&per_fact, &n_facts), &duration), &facts_in_db)) in self |
| 126 | + .per_fact_durations |
| 127 | + .iter() |
| 128 | + .zip(self.n_facts.iter()) |
| 129 | + .zip(self.block_durations.iter()) |
| 130 | + .zip(self.facts_in_db.iter()) |
| 131 | + .enumerate() |
| 132 | + { |
| 133 | + wtr.write_record(&[ |
| 134 | + i.to_string(), |
| 135 | + n_facts.to_string(), |
| 136 | + facts_in_db.to_string(), |
| 137 | + per_fact.to_string(), |
| 138 | + duration.to_string(), |
| 139 | + ]) |
| 140 | + .expect("Failed to write CSV record."); |
| 141 | + } |
| 142 | + wtr.flush().expect("Failed to flush CSV writer."); |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +pub async fn run_storage_benchmark(n_iterations: usize, output_dir: &str) { |
| 147 | + let seed = 42_u64; // Constant seed for reproducibility |
| 148 | + |
| 149 | + let mut rng = StdRng::seed_from_u64(seed); |
| 150 | + let mut time_measurement = TimeMeasurement::new(n_iterations); |
| 151 | + |
| 152 | + let mut storage = MapStorage::default(); |
| 153 | + let mut contracts_trie_root_hash = HashOutput::default(); |
| 154 | + let mut classes_trie_root_hash = HashOutput::default(); |
| 155 | + |
| 156 | + for i in 0..n_iterations { |
| 157 | + info!("Committer storage benchmark iteration {}/{}", i + 1, n_iterations); |
| 158 | + let input = InputImpl { |
| 159 | + state_diff: generate_random_state_diff(&mut rng), |
| 160 | + contracts_trie_root_hash, |
| 161 | + classes_trie_root_hash, |
| 162 | + config: ConfigImpl::default(), |
| 163 | + }; |
| 164 | + |
| 165 | + time_measurement.start_measurement(); |
| 166 | + let filled_forest = |
| 167 | + commit_block(input, &mut storage).await.expect("Failed to commit the given block."); |
| 168 | + let n_new_facts = filled_forest.write_to_storage(&mut storage); |
| 169 | + |
| 170 | + time_measurement.stop_measurement(n_new_facts); |
| 171 | + |
| 172 | + contracts_trie_root_hash = filled_forest.get_contract_root_hash(); |
| 173 | + classes_trie_root_hash = filled_forest.get_compiled_class_root_hash(); |
| 174 | + } |
| 175 | + |
| 176 | + time_measurement.pretty_print(50); |
| 177 | + time_measurement.to_csv(&format!("{n_iterations}.csv"), output_dir); |
| 178 | +} |
0 commit comments