use std::{fs::File, io::Write}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn write_buf(w: &mut impl Write) -> Result<(), std::io::Error> { let mut buf = [0u8; 10]; buf[0] = 0; buf[1] = 1; buf[2] = 2; buf[3] = 3; buf[4] = 4; buf[5] = 5; buf[6] = 6; buf[7] = 7; buf[8] = 8; buf[9] = 9; w.write_all(&buf)?; Ok(()) } fn write_many(w: &mut impl Write) -> Result<(), std::io::Error> { w.write_all(&[0])?; w.write_all(&[1])?; w.write_all(&[2])?; w.write_all(&[3])?; w.write_all(&[4])?; w.write_all(&[5])?; w.write_all(&[6])?; w.write_all(&[7])?; w.write_all(&[8])?; w.write_all(&[9])?; Ok(()) } pub fn criterion_benchmark(c: &mut Criterion) { _ = std::fs::remove_file("/tmp/write_buf"); let mut file = File::create("/tmp/write_buf").unwrap(); c.bench_function("write_buf", |b| { b.iter(|| write_buf(&mut file).expect("written")) }); _ = std::fs::remove_file("/tmp/write_many"); let mut file = File::create("/tmp/write_many").unwrap(); c.bench_function("write_many", |b| { b.iter(|| write_many(&mut file).expect("written")) }); _ = std::fs::remove_file("/tmp/write_many_buf"); let file = File::create("/tmp/write_many_buf").unwrap(); let mut w = std::io::BufWriter::new(file); c.bench_function("write_many_buf", |b| { b.iter(|| write_many(&mut w).expect("written")) }); _ = std::fs::remove_file("/tmp/write_buf_buf"); let file = File::create("/tmp/write_buf_buf").unwrap(); let mut w = std::io::BufWriter::new(file); c.bench_function("write_buf_buf", |b| { b.iter(|| write_buf(&mut w).expect("written")) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);