reth_primitives_traits/constants/
gas_units.rs

1use alloc::string::String;
2use core::time::Duration;
3
4/// Represents one Kilogas, or `1_000` gas.
5pub const KILOGAS: u64 = 1_000;
6
7/// Represents one Megagas, or `1_000_000` gas.
8pub const MEGAGAS: u64 = KILOGAS * 1_000;
9
10/// Represents one Gigagas, or `1_000_000_000` gas.
11pub const GIGAGAS: u64 = MEGAGAS * 1_000;
12
13/// Returns a formatted gas throughput log, showing either:
14///  * "Kgas/s", or 1,000 gas per second
15///  * "Mgas/s", or 1,000,000 gas per second
16///  * "Ggas/s", or 1,000,000,000 gas per second
17///
18/// Depending on the magnitude of the gas throughput.
19pub 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
30/// Returns a formatted gas log, showing either:
31///  * "Kgas", or 1,000 gas
32///  * "Mgas", or 1,000,000 gas
33///  * "Ggas", or 1,000,000,000 gas
34///
35/// Depending on the magnitude of gas.
36pub 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 = 100_000;
54        let gas_unit = format_gas(gas);
55        assert_eq!(gas_unit, "100.00 Kgas");
56
57        let gas = 100_000_000;
58        let gas_unit = format_gas(gas);
59        assert_eq!(gas_unit, "100.00 Mgas");
60
61        let gas = 100_000_000_000;
62        let gas_unit = format_gas(gas);
63        assert_eq!(gas_unit, "100.00 Ggas");
64    }
65
66    #[test]
67    fn test_gas_throughput_fmt() {
68        let duration = Duration::from_secs(1);
69        let gas = 100_000;
70        let throughput = format_gas_throughput(gas, duration);
71        assert_eq!(throughput, "100.00 Kgas/second");
72
73        let gas = 100_000_000;
74        let throughput = format_gas_throughput(gas, duration);
75        assert_eq!(throughput, "100.00 Mgas/second");
76
77        let gas = 100_000_000_000;
78        let throughput = format_gas_throughput(gas, duration);
79        assert_eq!(throughput, "100.00 Ggas/second");
80    }
81}