如何从代码本身获取 Rust 中对象占用的内存

Lah*_*nga 5 memory hashmap rust

我需要根据一些事件读取对象占用的内存。我可以从标准库中使用一种简单的方法吗?我需要访问以下包含嵌套结构的对象的内存使用情况。

HashMap<String, HashMap<AppIdentifier, HashMap<String, u64>>>
Run Code Online (Sandbox Code Playgroud)

egg*_*yal 7

self我建议您使用返回的传递拥有的分配大小的方法创建一个特征:

trait AllocatedSize {
    fn allocated_size(&self) -> usize;
}
Run Code Online (Sandbox Code Playgroud)

然后对涉及的所有内容实施该操作:

impl AllocatedSize for u64 {
    fn allocated_size(&self) -> usize {
        0
    }
}

impl AllocatedSize for String {
    fn allocated_size(&self) -> usize {
        self.capacity()
    }
}

impl AllocatedSize for AppIdentifier {
    fn allocated_size(&self) -> usize {
        todo!()
    }
}

impl<K: AllocatedSize, V: AllocatedSize> AllocatedSize for HashMap<K, V> {
    fn allocated_size(&self) -> usize {
        // every element in the map directly owns its key and its value
        const ELEMENT_SIZE: usize = std::mem::size_of::<K>() + std::mem::size_of::<V>();

        // directly owned allocation
        // NB: self.capacity() may be an underestimate, see its docs
        // NB: also ignores control bytes, see hashbrown implementation
        let directly_owned = self.capacity() * ELEMENT_SIZE;

        // transitively owned allocations
        let transitively_owned = self
            .iter()
            .map(|(key, val)| key.allocated_size() + val.allocated_size())
            .sum();

        directly_owned + transitively_owned
    }
}
Run Code Online (Sandbox Code Playgroud)