如何从代码本身获取rust中对象占用的内存
How to get memory occupied by an object in rust from the code itself
我有一个需求,需要根据一些事件读取一个对象占用的内存。有没有我可以从标准库中使用的简单方法?我需要访问以下包含嵌套结构的对象的内存使用情况。
HashMap<String, HashMap<AppIdentifier, HashMap<String, u64>>>
我建议您使用 returns self
的可传递拥有分配的大小的方法创建特征:
trait AllocatedSize {
fn allocated_size(&self) -> usize;
}
然后对涉及的所有内容实施:
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
}
}
我有一个需求,需要根据一些事件读取一个对象占用的内存。有没有我可以从标准库中使用的简单方法?我需要访问以下包含嵌套结构的对象的内存使用情况。
HashMap<String, HashMap<AppIdentifier, HashMap<String, u64>>>
我建议您使用 returns self
的可传递拥有分配的大小的方法创建特征:
trait AllocatedSize {
fn allocated_size(&self) -> usize;
}
然后对涉及的所有内容实施:
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
}
}