Skip to content

Commit 830ef73

Browse files
committed
Add a test case for jemallocator as the global allocator
1 parent d641f9b commit 830ef73

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

tests/test_jemallocator.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// -*- coding:utf-8-unix -*-
2+
3+
use jemalloc_ctl;
4+
use jemallocator;
5+
6+
#[global_allocator]
7+
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
8+
9+
type UnitResult = Result<(), Box<dyn std::error::Error>>;
10+
11+
fn main() -> UnitResult {
12+
do_allocate_heap()
13+
}
14+
15+
#[test]
16+
fn test_jemallocator() -> UnitResult {
17+
do_allocate_heap()
18+
}
19+
20+
fn do_allocate_heap() -> UnitResult {
21+
use jemalloc_ctl::{epoch, stats};
22+
use rand::prelude::*;
23+
24+
const SIZE: usize = 100000;
25+
26+
let mut rng = SmallRng::from_rng(thread_rng())?;
27+
28+
let v = rng
29+
.sample_iter(&rand::distributions::Standard)
30+
.take(SIZE)
31+
.collect::<Vec<usize>>();
32+
let v_byte_size = v.len() * std::mem::size_of::<usize>();
33+
34+
// many statistics are cached and only updated when the epoch is advanced.
35+
epoch::advance().map_err(stringify)?;
36+
let allocated = stats::allocated::read().map_err(stringify)?;
37+
let resident = stats::resident::read().map_err(stringify)?;
38+
println!(
39+
"{} bytes used by a Vec<uzize> with len {}.",
40+
v_byte_size,
41+
v.len()
42+
);
43+
println!(
44+
"{} bytes allocated/{} bytes resident using jemalloc",
45+
allocated, resident
46+
);
47+
48+
assert!(
49+
allocated >= v_byte_size,
50+
"allocated size ({} bytes) is smaller than the vector size ({} bytes).",
51+
allocated,
52+
v_byte_size,
53+
);
54+
55+
// to prevent the compiler to optimize the vec out, read its value at
56+
// a random location.
57+
let i = rng.gen_range(0, SIZE);
58+
println!("v[{}] = {}", i, v[i]);
59+
60+
Ok(())
61+
}
62+
63+
fn stringify(x: impl ToString) -> String {
64+
x.to_string()
65+
}

0 commit comments

Comments
 (0)