#[derive(Debug, Clone, Default)]
pub struct IOStats {
pub read_count: Option<u64>,
pub write_count: Option<u64>,
pub read_bytes: u64,
pub write_bytes: u64,
}
pub fn get_process_io_stats()
-> anyhow::Result<IOStats>
{
#[cfg(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "windows"
))]
{
return get_process_io_stats_impl();
}
anyhow::bail!("cannot get I/O stats: this platform is not supported");
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn get_process_io_stats_impl()
-> anyhow::Result<IOStats>
{
use procfs::process::Process;
let ret = Process::myself()?.io()?;
Ok(IOStats {
read_count: Some(ret.syscr),
write_count: Some(ret.syscw),
read_bytes: ret.read_bytes,
write_bytes: ret.write_bytes,
})
}
#[cfg(target_os = "windows")]
fn get_process_io_stats_impl()
-> anyhow::Result<IOStats>
{
use core::mem::MaybeUninit;
use windows_sys::Win32::System::Threading::{
GetCurrentProcess,
GetProcessIoCounters,
IO_COUNTERS,
};
let mut io_counters =
MaybeUninit::<IO_COUNTERS>::uninit();
let ret = unsafe {
GetProcessIoCounters(
GetCurrentProcess(),
io_counters.as_mut_ptr(),
)
};
if ret == 0 {
return Err(
std::io::Error::last_os_error().into()
);
}
let ic = unsafe { io_counters.assume_init() };
Ok(IOStats {
read_count: Some(ic.ReadOperationCount),
write_count: Some(ic.WriteOperationCount),
read_bytes: ic.ReadTransferCount,
write_bytes: ic.WriteTransferCount,
})
}
#[cfg(target_os = "macos")]
fn get_process_io_stats_impl()
-> anyhow::Result<IOStats>
{
use libc::{rusage_info_v2, RUSAGE_INFO_V2};
use core::{mem::MaybeUninit, ffi::c_int};
let mut rusage_info_v2 =
MaybeUninit::<rusage_info_v2>::uninit();
let ret_code = unsafe {
libc::proc_pid_rusage(
std::process::id() as c_int,
RUSAGE_INFO_V2,
rusage_info_v2.as_mut_ptr() as *mut _,
)
};
if ret_code != 0 {
return Err(
std::io::Error::last_os_error().into()
);
}
let ri_v2 = unsafe { rusage_info_v2.assume_init() };
Ok(IOStats {
read_count: None,
write_count: None,
read_bytes: ri_v2.ri_diskio_bytesread,
write_bytes: ri_v2.ri_diskio_byteswritten,
})
}