Files
a0_basic_app
a1_vehicle
a2_async_sim
ab_glyph
ab_glyph_rasterizer
adler
adler32
agents
aho_corasick
anyhow
approx
aquamarine
ash
atty
bitflags
bytemuck
byteorder
cache_padded
cfg_if
chrono
color_quant
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
deflate
draw2d
either
flexi_logger
generic_array
gif
glfw
glfw_sys
glob
image
indoc
itertools
jpeg_decoder
lazy_static
libc
libloading
log
matrixmultiply
memchr
memoffset
miniz_oxide
nalgebra
base
geometry
linalg
third_party
num_complex
num_cpus
num_integer
num_iter
num_rational
num_traits
owned_ttf_parser
paste
png
proc_macro2
proc_macro_error
proc_macro_error_attr
quote
raw_window_handle
rawpointer
rayon
rayon_core
regex
regex_syntax
scoped_threadpool
scopeguard
semver
semver_parser
serde
serde_derive
simba
smawk
spin_sleep
syn
terminal_size
textwrap
thiserror
thiserror_impl
tiff
time
triple_buffer
ttf_parser
typenum
unicode_width
unicode_xid
unindent
vk_sys
weezl
yansi
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use super::{Metrics, MetricsReport};

use std::collections::HashMap;

use ash::vk;

/// Build a human-friendly markdown report which is printed directly to the
/// console.
///
/// Reports Look similar to the following:-
///
/// ```markdown
/// # Device Allocator - Memory Report Totals
///
///   |                Metric Name | Value        |
///   | -------------------------- | ------------ |
///   | max concurrent allocations | 6            |
///   |     total allocation count | 7            |
///   |    leaked allocation count | 0            |
///   |       mean allocation size | 25.07 KiB    |
///   |         biggest allocation | 87 KiB       |
///   |        smallest allocation | 256 B        |
///
///
/// ## Metrics By Memory Type Index
///
/// ### Memory Type 7
///
///   |                Metric Name | Value        |
///   | -------------------------- | ------------ |
///   | max concurrent allocations | 2            |
///   |     total allocation count | 2            |
///   |    leaked allocation count | 0            |
///   |       mean allocation size | 43.75 KiB    |
///   |         biggest allocation | 87 KiB       |
///   |        smallest allocation | 512 B        |
///
/// ### Memory Type 8
///
///   |                Metric Name | Value        |
///   | -------------------------- | ------------ |
///   | max concurrent allocations | 4            |
///   |     total allocation count | 5            |
///   |    leaked allocation count | 0            |
///   |       mean allocation size | 17.599 KiB   |
///   |         biggest allocation | 85.5 KiB     |
///   |        smallest allocation | 256 B        |
/// ```
///
pub struct ConsoleMarkdownReport {
    ash_instance: ash::Instance,
    physical_device: vk::PhysicalDevice,
}

impl ConsoleMarkdownReport {
    const BASE: u64 = 1024;
    const UNITS: [&'static str; 4] = ["B", "KiB", "MiB", "GiB"];

    /// Create a report which renders metrics as markdown on the terminal.
    ///
    /// The caller is responsible for ensuring that the instance and
    /// physical device both live for at least as long as the report.
    pub fn new(
        ash_instance: ash::Instance,
        physical_device: vk::PhysicalDevice,
    ) -> Self {
        Self {
            ash_instance,
            physical_device,
        }
    }

    fn formatted_metrics_list(metrics: &Metrics) -> String {
        indoc::formatdoc!(
            "
            {indent}|                Metric Name | {header:<12} |
            {indent}| -------------------------- | {underline:<12} |
            {indent}| max concurrent allocations | {:<12} |
            {indent}|     total allocation count | {:<12} |
            {indent}|    leaked allocation count | {:<12} |
            {indent}|       mean allocation size | {:<12} |
            {indent}|         biggest allocation | {:<12} |
            {indent}|        smallest allocation | {:<12} |
            ",
            metrics.max_concurrent_allocations,
            metrics.total_allocations,
            metrics.current_allocations,
            Self::pretty_print_bytes(metrics.mean_allocation_byte_size),
            Self::pretty_print_bytes(metrics.biggest_allocation),
            Self::pretty_print_bytes(metrics.smallest_allocation),
            header = "Value",
            underline = "------------",
            indent = "  ",
        )
    }

    fn heap_description(&self, memory_type_index: u32) -> String {
        use ash::version::InstanceV1_0;

        let properties = unsafe {
            self.ash_instance
                .get_physical_device_memory_properties(self.physical_device)
        };

        let memory_properties =
            properties.memory_types[memory_type_index as usize];

        indoc::formatdoc!(
            "
            ### Heap {heap} - Memory Type Index {type_index}

            Properties: {properties:?}
            ",
            heap = memory_properties.heap_index,
            type_index = memory_type_index,
            properties = memory_properties.property_flags
        )
    }

    fn pretty_print_bytes(byte_size: u64) -> String {
        let order_of_magnitude = Self::order_of_magnitude(byte_size);
        let divisor = Self::BASE.pow(order_of_magnitude as u32);

        // This weird bit of gymnastics ensures that there are at *most* 3
        // numbers after the decimal, but only if the precision is actually
        // needed. (e.g. 256.000 will render as just 256 in the final report)
        let full_print = format!("{:.3}", byte_size as f32 / divisor as f32);
        let truncated: f32 = full_print.parse().unwrap();

        format!(
            "{size} {unit}",
            size = truncated,
            unit = Self::UNITS[order_of_magnitude]
        )
    }

    /// Compute the order of magnitude in units of 1024.
    ///
    /// This could probably be improved with some logarithms (division in a
    /// loop, I'm looking at you!), but the while loop works just fine.
    fn order_of_magnitude(byte_size: u64) -> usize {
        let mut order_of_magnitude = 0;
        let mut remaining_precision = byte_size as f64;
        while remaining_precision >= 1.0 {
            remaining_precision /= 1024.0;
            order_of_magnitude += 1;
        }
        if order_of_magnitude > 0 {
            order_of_magnitude -= 1;
        }
        order_of_magnitude.min(Self::UNITS.len())
    }
}

impl MetricsReport for ConsoleMarkdownReport {
    fn render(
        &self,
        name: &str,
        total: &Metrics,
        metrics_by_type: &HashMap<u32, Metrics>,
    ) {
        let mut report = indoc::formatdoc!(
            "

            # {name} - Memory Report Totals

            {totals}

            ## Metrics By Memory Type Index

            ",
            name = name,
            totals = Self::formatted_metrics_list(total)
        );

        for (memory_type_index, metrics) in metrics_by_type {
            report += indoc::formatdoc!(
                "
                {heap_description}
                {metrics}
                ",
                heap_description = self.heap_description(*memory_type_index),
                metrics = Self::formatted_metrics_list(&metrics),
            )
            .as_ref();
        }

        log::info!("{}", report);
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    pub fn test_pretty_print_bytes() {
        use ConsoleMarkdownReport as CMR;

        assert_eq!(CMR::pretty_print_bytes(1), "1 B");
        assert_eq!(CMR::pretty_print_bytes(1024), "1 KiB");
        assert_eq!(CMR::pretty_print_bytes(1024 * 1024), "1 MiB");
        assert_eq!(CMR::pretty_print_bytes(1024 * 1024 * 1024), "1 GiB");

        assert_eq!(CMR::pretty_print_bytes(1000), "1000 B");
        assert_eq!(CMR::pretty_print_bytes(1034), "1.01 KiB");
        assert_eq!(CMR::pretty_print_bytes(2048), "2 KiB");
        assert_eq!(CMR::pretty_print_bytes(4096), "4 KiB");
        assert_eq!(CMR::pretty_print_bytes(34235), "33.433 KiB");
    }
}