Skip to main content

simple_process_stats/
lib.rs

1#![deny(clippy::all)]
2#![deny(clippy::cargo)]
3
4//! A small library to get memory usage and elapsed CPU time.
5//!
6//! Supports Windows, Linux and macOS.
7//!
8//! ```rust
9//! use simple_process_stats::ProcessStats;
10//!
11//! # fn main() {
12//! let process_stats = ProcessStats::get().expect("could not get stats for running process");
13//! println!("{:?}", process_stats);
14//! // ProcessStats {
15//! //     cpu_time_user: 421.875ms,
16//! //     cpu_time_kernel: 102.332ms,
17//! //     memory_usage_bytes: 3420160,
18//! // }
19//! # }
20//! ```
21//!
22//! On Linux, this library reads `/proc/self/stat` and uses the `sysconf` libc function.
23//!
24//! On Windows, the library uses `GetCurrentProcess` combined with `GetProcessTimes` and `K32GetProcessMemoryInfo`.
25//!
26//! On macOS, this library uses `proc_pidinfo` from `libproc` (and current process ID is determined via `libc`).
27
28#[cfg(target_os = "linux")]
29mod linux;
30#[cfg(target_os = "macos")]
31mod macos;
32#[cfg(target_os = "windows")]
33mod windows;
34
35use std::path::PathBuf;
36use std::time::Duration;
37use thiserror::Error;
38
39/// Holds the retrieved basic statistics about the running process.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub struct ProcessStats {
42    /// How much time this process has spent executing in user mode since it was started
43    pub cpu_time_user: Duration,
44    /// How much time this process has spent executing in kernel mode since it was started
45    pub cpu_time_kernel: Duration,
46    /// Size of the "resident" memory the process has allocated, in bytes.
47    pub memory_usage_bytes: u64,
48}
49
50impl ProcessStats {
51    /// Get the statistics using the OS-specific method.
52    #[cfg(target_os = "windows")]
53    pub fn get() -> Result<ProcessStats, Error> {
54        windows::get_info()
55    }
56
57    /// Get the statistics using the OS-specific method.
58    #[cfg(target_os = "linux")]
59    pub fn get() -> Result<ProcessStats, Error> {
60        linux::get_info()
61    }
62
63    /// Get the statistics using the OS-specific method.
64    #[cfg(target_os = "macos")]
65    pub fn get() -> Result<ProcessStats, Error> {
66        macos::get_info()
67    }
68}
69
70/// An error that occurred while trying to get the process stats.
71#[derive(Error, Debug)]
72pub enum Error {
73    /// A file's contents could not be read successfully. The file that could not be read is specified by
74    /// the `PathBuf` parameter.
75    #[error("Failed to read from file `{0}`: {1}")]
76    FileRead(PathBuf, std::io::Error),
77    /// A file's contents were in an unexpected format
78    #[error("File contents are in unexpected format")]
79    FileContentsMalformed,
80
81    /// A system-native function returned an error code.
82    #[error("Call to system-native API failed: {0}")]
83    SystemCall(std::io::Error),
84}