58 lines
1.6 KiB
Rust
58 lines
1.6 KiB
Rust
use std::io::Write;
|
|
use std::fs::OpenOptions;
|
|
use std::time::Instant;
|
|
|
|
fn allocate_chunk(src: &[u8], size: usize) -> Result<(), std::io::Error> {
|
|
let mut file = OpenOptions::new()
|
|
.read(false)
|
|
.write(true)
|
|
.create(true)
|
|
.open("/tmp/testfile")?;
|
|
|
|
//truncate file
|
|
file.set_len(size as u64)?;
|
|
|
|
let mut bytes_written = 0;
|
|
let offset = size - src.len();
|
|
// write just just before EOF
|
|
while bytes_written < offset {
|
|
let len = file.write(&src)?;
|
|
bytes_written += len;
|
|
}
|
|
// write the exact remaining amount
|
|
if bytes_written < size {
|
|
file.write_all(&src[..size - bytes_written])?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
macro_rules! benchmark_zerofill {
|
|
($num:expr, $buf:expr, $size:expr) => {
|
|
let count: usize = 1024 * 1024 * $size;
|
|
let start = Instant::now();
|
|
if $buf <= 16384 {
|
|
let buf: [u8; $buf] = [0x41; $buf];
|
|
for _ in 0..$num {
|
|
allocate_chunk(&buf, count).unwrap();
|
|
}
|
|
}
|
|
else { // default stack for threads is 2 MiB, use heap > 16384
|
|
let buf: Vec<u8> = vec![0x41; $buf];
|
|
for _ in 0..$num {
|
|
allocate_chunk(&buf, count).unwrap();
|
|
}
|
|
}
|
|
let end = Instant::now();
|
|
println!("{} {:?}", $buf, end.duration_since(start));
|
|
};
|
|
}
|
|
|
|
fn main() {
|
|
// loops, buffer size, file size
|
|
benchmark_zerofill!(1000, 1024, 256);
|
|
benchmark_zerofill!(1000, 2048, 256);
|
|
benchmark_zerofill!(1000, 4096, 256);
|
|
benchmark_zerofill!(1000, 8192, 256);
|
|
benchmark_zerofill!(1000, 16384, 256);
|
|
benchmark_zerofill!(1000, 4194304, 256);
|
|
}
|