MST
星途 面试题库

面试题:Rust线程性能监测基础

在Rust中,如何使用标准库提供的工具来监测线程的CPU使用率?请简述主要步骤并给出简单示例代码。
42.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 主要步骤
    • 使用std::process::Command来执行系统命令获取CPU使用信息。在类Unix系统中,可以使用ps命令,在Windows系统中,可以使用Get-Process命令(通过PowerShell)。
    • 解析命令输出以提取目标线程的CPU使用率。
    • 可以在一个循环中定期执行这些操作来持续监测。
  2. 示例代码(以类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使用率进行输出,每秒获取一次。在实际使用中,可根据具体需求进行调整,如获取其他线程或对不同操作系统做适配。