reth_primitives_traits/constants/
gas_units.rs1use alloc::string::String;
2use core::time::Duration;
3
4pub const KILOGAS: u64 = 1_000;
6
7pub const MEGAGAS: u64 = KILOGAS * 1_000;
9
10pub const GIGAGAS: u64 = MEGAGAS * 1_000;
12
13pub fn format_gas_throughput(gas: u64, execution_duration: Duration) -> String {
20 let gas_per_second = gas as f64 / execution_duration.as_secs_f64();
21 if gas_per_second < MEGAGAS as f64 {
22 format!("{:.2}Kgas/second", gas_per_second / KILOGAS as f64)
23 } else if gas_per_second < GIGAGAS as f64 {
24 format!("{:.2}Mgas/second", gas_per_second / MEGAGAS as f64)
25 } else {
26 format!("{:.2}Ggas/second", gas_per_second / GIGAGAS as f64)
27 }
28}
29
30pub fn format_gas(gas: u64) -> String {
37 let gas = gas as f64;
38 if gas < MEGAGAS as f64 {
39 format!("{:.2}Kgas", gas / KILOGAS as f64)
40 } else if gas < GIGAGAS as f64 {
41 format!("{:.2}Mgas", gas / MEGAGAS as f64)
42 } else {
43 format!("{:.2}Ggas", gas / GIGAGAS as f64)
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn test_gas_fmt() {
53 let gas = 888;
54 let gas_unit = format_gas(gas);
55 assert_eq!(gas_unit, "0.89Kgas");
56
57 let gas = 100_000;
58 let gas_unit = format_gas(gas);
59 assert_eq!(gas_unit, "100.00Kgas");
60
61 let gas = 100_000_000;
62 let gas_unit = format_gas(gas);
63 assert_eq!(gas_unit, "100.00Mgas");
64
65 let gas = 100_000_000_000;
66 let gas_unit = format_gas(gas);
67 assert_eq!(gas_unit, "100.00Ggas");
68 }
69
70 #[test]
71 fn test_gas_throughput_fmt() {
72 let duration = Duration::from_secs(1);
73 let gas = 100_000;
74 let throughput = format_gas_throughput(gas, duration);
75 assert_eq!(throughput, "100.00Kgas/second");
76
77 let gas = 100_000_000;
78 let throughput = format_gas_throughput(gas, duration);
79 assert_eq!(throughput, "100.00Mgas/second");
80
81 let gas = 100_000_000_000;
82 let throughput = format_gas_throughput(gas, duration);
83 assert_eq!(throughput, "100.00Ggas/second");
84 }
85}