|
| 1 | +use std::cmp::{max, min}; |
| 2 | +use std::fs::File; |
| 3 | +use std::io::Write; |
| 4 | +use std::time::{Duration, SystemTime}; |
| 5 | + |
| 6 | +#[derive(Debug)] |
| 7 | +pub struct StorageBenchmark { |
| 8 | + pub path: String, |
| 9 | + pub file_size: usize, |
| 10 | + pub chunk_size: usize, |
| 11 | + pub loop_times: usize, |
| 12 | +} |
| 13 | + |
| 14 | +impl StorageBenchmark { |
| 15 | + pub fn run_once(&self) -> anyhow::Result<Duration> { |
| 16 | + log::info!("Running write test with config={self:#?}"); |
| 17 | + let buf: Vec<u8> = vec![1; self.chunk_size]; |
| 18 | + let mut remaining_size = self.file_size; |
| 19 | + |
| 20 | + let start = SystemTime::now(); |
| 21 | + let mut file = File::open(&self.path)?; |
| 22 | + while true { |
| 23 | + let chunk_size = max(self.chunk_size, remaining_size); |
| 24 | + let written = file.write(&buf[..chunk_size])?; |
| 25 | + remaining_size -= written; |
| 26 | + } |
| 27 | + file.sync_all(); |
| 28 | + let end = SystemTime::now(); |
| 29 | + let duration = end.duration_since(start)?; |
| 30 | + log::info!("Finish write test with total time {duration}"); |
| 31 | + log::info!( |
| 32 | + "throughput={:,} MB/s", |
| 33 | + ((self.file_size as f64) / (1024.0 * 1024.0)) / (duration.as_secs() as f64) |
| 34 | + ); |
| 35 | + Ok(duration) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn run(&self) -> anyhow::Result<()> { |
| 39 | + let mut durations = Vec::<Duration>::with_capacity(self.loop_times); |
| 40 | + for idx in (0..self.loop_times) { |
| 41 | + log::info!( |
| 42 | + "Running write test for {} out of {} time", |
| 43 | + idx + 1, |
| 44 | + self.loop_times |
| 45 | + ); |
| 46 | + let duration = self.run_once()?; |
| 47 | + durations.push(duration); |
| 48 | + } |
| 49 | + |
| 50 | + let total = durations.iter().sum(); |
| 51 | + log::info!( |
| 52 | + "Finish {} write test with total time {}", |
| 53 | + self.loop_times, |
| 54 | + total |
| 55 | + ); |
| 56 | + log::info!( |
| 57 | + "avg throughput={:,} MB/s", |
| 58 | + ((self.file_size as f64) * self.loop_times / (1024.0 * 1024.0)) |
| 59 | + / (total.as_secs() as f64) |
| 60 | + ); |
| 61 | + |
| 62 | + Ok(()) |
| 63 | + } |
| 64 | +} |
0 commit comments