reth_bench/bench/
output.rs

1//! Contains various benchmark output formats, either for logging or for
2//! serialization to / from files.
3
4use eyre::OptionExt;
5use reth_primitives_traits::constants::GIGAGAS;
6use serde::{ser::SerializeStruct, Serialize};
7use std::time::Duration;
8
9/// This is the suffix for gas output csv files.
10pub(crate) const GAS_OUTPUT_SUFFIX: &str = "total_gas.csv";
11
12/// This is the suffix for combined output csv files.
13pub(crate) const COMBINED_OUTPUT_SUFFIX: &str = "combined_latency.csv";
14
15/// This is the suffix for new payload output csv files.
16pub(crate) const NEW_PAYLOAD_OUTPUT_SUFFIX: &str = "new_payload_latency.csv";
17
18/// This represents the results of a single `newPayload` call in the benchmark, containing the gas
19/// used and the `newPayload` latency.
20#[derive(Debug)]
21pub(crate) struct NewPayloadResult {
22    /// The gas used in the `newPayload` call.
23    pub(crate) gas_used: u64,
24    /// The latency of the `newPayload` call.
25    pub(crate) latency: Duration,
26}
27
28impl NewPayloadResult {
29    /// Returns the gas per second processed in the `newPayload` call.
30    pub(crate) fn gas_per_second(&self) -> f64 {
31        self.gas_used as f64 / self.latency.as_secs_f64()
32    }
33}
34
35impl std::fmt::Display for NewPayloadResult {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        write!(
38            f,
39            "New payload processed at {:.4} Ggas/s, used {} total gas. Latency: {:?}",
40            self.gas_per_second() / GIGAGAS as f64,
41            self.gas_used,
42            self.latency
43        )
44    }
45}
46
47/// This is another [`Serialize`] implementation for the [`NewPayloadResult`] struct, serializing
48/// the duration as microseconds because the csv writer would fail otherwise.
49impl Serialize for NewPayloadResult {
50    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
51    where
52        S: serde::ser::Serializer,
53    {
54        // convert the time to microseconds
55        let time = self.latency.as_micros();
56        let mut state = serializer.serialize_struct("NewPayloadResult", 2)?;
57        state.serialize_field("gas_used", &self.gas_used)?;
58        state.serialize_field("latency", &time)?;
59        state.end()
60    }
61}
62
63/// This represents the combined results of a `newPayload` call and a `forkchoiceUpdated` call in
64/// the benchmark, containing the gas used, the `newPayload` latency, and the `forkchoiceUpdated`
65/// latency.
66#[derive(Debug)]
67pub(crate) struct CombinedResult {
68    /// The block number of the block being processed.
69    pub(crate) block_number: u64,
70    /// The `newPayload` result.
71    pub(crate) new_payload_result: NewPayloadResult,
72    /// The latency of the `forkchoiceUpdated` call.
73    pub(crate) fcu_latency: Duration,
74    /// The latency of both calls combined.
75    pub(crate) total_latency: Duration,
76}
77
78impl CombinedResult {
79    /// Returns the gas per second, including the `newPayload` _and_ `forkchoiceUpdated` duration.
80    pub(crate) fn combined_gas_per_second(&self) -> f64 {
81        self.new_payload_result.gas_used as f64 / self.total_latency.as_secs_f64()
82    }
83}
84
85impl std::fmt::Display for CombinedResult {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        write!(
88            f,
89            "Payload {} processed at {:.4} Ggas/s, used {} total gas. Combined gas per second: {:.4} Ggas/s. fcu latency: {:?}, newPayload latency: {:?}",
90            self.block_number,
91            self.new_payload_result.gas_per_second() / GIGAGAS as f64,
92            self.new_payload_result.gas_used,
93            self.combined_gas_per_second() / GIGAGAS as f64,
94            self.fcu_latency,
95            self.new_payload_result.latency
96        )
97    }
98}
99
100/// This is a [`Serialize`] implementation for the [`CombinedResult`] struct, serializing the
101/// durations as microseconds because the csv writer would fail otherwise.
102impl Serialize for CombinedResult {
103    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
104    where
105        S: serde::ser::Serializer,
106    {
107        // convert the time to microseconds
108        let fcu_latency = self.fcu_latency.as_micros();
109        let new_payload_latency = self.new_payload_result.latency.as_micros();
110        let total_latency = self.total_latency.as_micros();
111        let mut state = serializer.serialize_struct("CombinedResult", 5)?;
112
113        // flatten the new payload result because this is meant for CSV writing
114        state.serialize_field("block_number", &self.block_number)?;
115        state.serialize_field("gas_used", &self.new_payload_result.gas_used)?;
116        state.serialize_field("new_payload_latency", &new_payload_latency)?;
117        state.serialize_field("fcu_latency", &fcu_latency)?;
118        state.serialize_field("total_latency", &total_latency)?;
119        state.end()
120    }
121}
122
123/// This represents a row of total gas data in the benchmark.
124#[derive(Debug)]
125pub(crate) struct TotalGasRow {
126    /// The block number of the block being processed.
127    pub(crate) block_number: u64,
128    /// The total gas used in the block.
129    pub(crate) gas_used: u64,
130    /// Time since the start of the benchmark.
131    pub(crate) time: Duration,
132}
133
134/// This represents the aggregated output, meant to show gas per second metrics, of a benchmark run.
135#[derive(Debug)]
136pub(crate) struct TotalGasOutput {
137    /// The total gas used in the benchmark.
138    pub(crate) total_gas_used: u64,
139    /// The total duration of the benchmark.
140    pub(crate) total_duration: Duration,
141    /// The total gas used per second.
142    pub(crate) total_gas_per_second: f64,
143    /// The number of blocks processed.
144    pub(crate) blocks_processed: u64,
145}
146
147impl TotalGasOutput {
148    /// Create a new [`TotalGasOutput`] from a list of [`TotalGasRow`].
149    pub(crate) fn new(rows: Vec<TotalGasRow>) -> eyre::Result<Self> {
150        // the duration is obtained from the last row
151        let total_duration = rows.last().map(|row| row.time).ok_or_eyre("empty results")?;
152        let blocks_processed = rows.len() as u64;
153        let total_gas_used: u64 = rows.into_iter().map(|row| row.gas_used).sum();
154        let total_gas_per_second = total_gas_used as f64 / total_duration.as_secs_f64();
155
156        Ok(Self { total_gas_used, total_duration, total_gas_per_second, blocks_processed })
157    }
158
159    /// Return the total gigagas per second.
160    pub(crate) fn total_gigagas_per_second(&self) -> f64 {
161        self.total_gas_per_second / GIGAGAS as f64
162    }
163}
164
165/// This serializes the `time` field of the [`TotalGasRow`] to microseconds.
166///
167/// This is essentially just for the csv writer, which would have headers
168impl Serialize for TotalGasRow {
169    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
170    where
171        S: serde::ser::Serializer,
172    {
173        // convert the time to microseconds
174        let time = self.time.as_micros();
175        let mut state = serializer.serialize_struct("TotalGasRow", 3)?;
176        state.serialize_field("block_number", &self.block_number)?;
177        state.serialize_field("gas_used", &self.gas_used)?;
178        state.serialize_field("time", &time)?;
179        state.end()
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use csv::Writer;
187    use std::io::BufRead;
188
189    #[test]
190    fn test_write_total_gas_row_csv() {
191        let row = TotalGasRow { block_number: 1, gas_used: 1_000, time: Duration::from_secs(1) };
192
193        let mut writer = Writer::from_writer(vec![]);
194        writer.serialize(row).unwrap();
195        let result = writer.into_inner().unwrap();
196
197        // parse into Lines
198        let mut result = result.as_slice().lines();
199
200        // assert header
201        let expected_first_line = "block_number,gas_used,time";
202        let first_line = result.next().unwrap().unwrap();
203        assert_eq!(first_line, expected_first_line);
204
205        let expected_second_line = "1,1000,1000000";
206        let second_line = result.next().unwrap().unwrap();
207        assert_eq!(second_line, expected_second_line);
208    }
209}