tibba_performance/
lib.rs

1// Copyright 2025 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cached::proc_macro::cached;
16use serde::{Deserialize, Serialize};
17use std::time::Duration;
18use sysinfo::{Pid, ProcessesToUpdate, System};
19
20/// Represents system resource usage information for a process
21#[derive(Debug, Default, Serialize, Deserialize, Clone)]
22pub struct ProcessSystemInfo {
23    /// Memory usage in bytes
24    pub memory_usage: u64,
25    /// CPU usage as a percentage (0-100)
26    pub cpu_usage: f32,
27    /// CPU time in milliseconds
28    pub cpu_time: u64,
29    /// Open files
30    pub open_files: Option<usize>,
31    /// Total number of written bytes.
32    pub total_written_bytes: u64,
33    /// Number of written bytes since the last refresh.
34    pub written_bytes: u64,
35    /// Total number of read bytes.
36    pub total_read_bytes: u64,
37    /// Number of read bytes since the last refresh.
38    pub read_bytes: u64,
39}
40
41/// Retrieves current system resource usage information for this process
42///
43/// Collects information about:
44/// - Memory usage
45/// - CPU usage percentage
46///
47/// # Returns
48/// Returns a `ProcessSystemInfo` struct containing the resource usage metrics.
49/// If any metrics cannot be retrieved, they will contain default values (0).
50#[cached(time = 10, sync_writes = "by_key")]
51pub fn get_process_system_info(pid: usize) -> ProcessSystemInfo {
52    // Initialize system information collector
53    let mut sys = System::new();
54    let pid = Pid::from(pid);
55    // Refresh CPU usage statistics
56    sys.refresh_processes(ProcessesToUpdate::Some(&[pid]), false);
57
58    // Get CPU usage for current process if available
59    sys.process(pid)
60        .map(|process| {
61            let disk_usage = process.disk_usage();
62            ProcessSystemInfo {
63                cpu_usage: process.cpu_usage(),
64                memory_usage: process.memory(),
65                cpu_time: process.accumulated_cpu_time(),
66                open_files: process.open_files(),
67                total_written_bytes: disk_usage.total_written_bytes,
68                written_bytes: disk_usage.written_bytes,
69                total_read_bytes: disk_usage.total_read_bytes,
70                read_bytes: disk_usage.read_bytes,
71            }
72        })
73        .unwrap_or_default()
74}