11个版本 (7个破坏性更新)

0.8.1 2023年9月21日
0.7.1 2023年9月21日
0.5.0 2020年12月6日

#60 in 内存管理

Download history 313/week @ 2024-03-14 533/week @ 2024-03-21 388/week @ 2024-03-28 275/week @ 2024-04-04 325/week @ 2024-04-11 377/week @ 2024-04-18 406/week @ 2024-04-25 416/week @ 2024-05-02 255/week @ 2024-05-09 305/week @ 2024-05-16 125/week @ 2024-05-23 270/week @ 2024-05-30 239/week @ 2024-06-06 254/week @ 2024-06-13 292/week @ 2024-06-20 86/week @ 2024-06-27

每月957次下载
6 crates 中使用

MIT/Apache

17KB
206 代码行

Crates.io Docs Build

allocation-counter

Rust库,用于在计数内存分配的同时运行代码。可用于探索内存分配使用情况,或在测试中断言不超过所需的内存分配数量。

它通过用自定义分配器替换系统分配器来实现,在每次内存分配之前增加线程局部计数器,然后委托给正常的系统分配器。

请参阅以下示例和crates文档以获取更多信息。

示例

作为依赖项添加 - 由于包括特性和替换全局内存分配器,您可能希望将其放在功能门后面

[features]
count-allocations = ["allocation-counter"]

[dependencies]
allocation-counter = { version = "0", optional = true }

现在可以编写测试来断言不超过所需的内存分配数量

#[cfg(feature = "count-allocations")]
#[test]
pub fn no_memory_allocations() {
    // Verify that no memory allocations are made:
    let info = allocation_counter::measure(|| {
        code_that_should_not_allocate();
    });
    assert_eq!(info.count_total, 0);

    // Let's use a case where some allocations are expected.
    let info = allocation_counter::measure(|| {
        code_that_should_allocate_a_little();
    });

    // Using a lower bound can help track behaviour over time:
    assert!((500..600).contains(&info.count_total));
    assert!((10_000..20_000).contains(&info.bytes_total));

    // Limit peak memory usage:
    assert!((100..200).contains(&info.count_max));
    assert!((1_000..2_000).contains(&info.bytes_max));

    // We don't want any leaks:
    assert_eq!(0, info.count_current);
    assert_eq!(0, info.bytes_current);

    // It's possible to opt out of counting allocations
    // for certain parts of the code flow:
    let info = allocation_counter::measure(|| {
        code_that_should_not_allocate();
        allocation_counter::opt_out(|| {
            external_code_that_should_not_be_tested();
        });
        code_that_should_not_allocate();
    });
    assert_eq!(0, info.count_total);
}

启用必要的功能后运行测试

cargo test --features count-allocations

无运行时依赖项