面试题答案
一键面试- 主要步骤:
- 使用
std::process::Command
来执行系统命令获取CPU使用信息。在类Unix系统中,可以使用ps
命令,在Windows系统中,可以使用Get-Process
命令(通过PowerShell)。 - 解析命令输出以提取目标线程的CPU使用率。
- 可以在一个循环中定期执行这些操作来持续监测。
- 使用
- 示例代码(以类Unix系统为例):
use std::process::Command;
fn main() {
let thread_id = std::thread::current().id();
loop {
let output = Command::new("ps")
.arg("-p")
.arg(std::process::id().to_string())
.arg("-L")
.arg("-o")
.arg("pcpu,tid")
.output()
.expect("Failed to execute command");
let output_str = String::from_utf8_lossy(&output.stdout);
for line in output_str.lines().skip(1) {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() == 2 && parts[1].parse::<u64>().unwrap() == thread_id.as_u64() {
let cpu_usage = parts[0].parse::<f32>().unwrap();
println!("CPU usage of thread {}: {}%", thread_id, cpu_usage);
}
}
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
此代码获取当前进程下所有线程的CPU使用率,并筛选出当前线程的CPU使用率进行输出,每秒获取一次。在实际使用中,可根据具体需求进行调整,如获取其他线程或对不同操作系统做适配。