当前位置: 首页 > news >正文

linux获取cpu使用率(sy%+us%)

float getCpuUsage() 
{
    // C++11兼容的元组解包
    typedef std::tuple<unsigned long long, unsigned long long, unsigned long long> CpuTuple;

    auto parseCpuLine = [](const std::string& line) -> CpuTuple {
        std::istringstream iss(line);
        iss.ignore(3, ' '); // 跳过 "cpu"
        while (iss.peek() == ' ' || iss.peek() == '\t') iss.ignore();

        // 解析所有字段(含 steal、guest、guest_nice)
        unsigned long long user = 0, nice = 0, system = 0, idle = 0,
            iowait = 0, irq = 0, softirq = 0, steal = 0,
            guest = 0, guest_nice = 0;
        iss >> user >> nice >> system >> idle >> iowait >> irq >> softirq
            >> steal >> guest >> guest_nice;

        // 计算用户态和系统态时间(us% = user + nice, sy% = system + irq + softirq)
        unsigned long long us_time = user + nice;
        unsigned long long sy_time = system + irq + softirq;
        // 总时间包含所有字段 [11](@ref)
        unsigned long long total = user + nice + system + idle + iowait +
            irq + softirq + steal + guest + guest_nice;

        return std::make_tuple(us_time, sy_time, total);
    };

    // 第一次采样
    std::ifstream file1("/proc/stat");
    std::string line1;
    std::getline(file1, line1);
    unsigned long long us1, sy1, total1;
    std::tie(us1, sy1, total1) = parseCpuLine(line1);

    sleep(1);

    // 第二次采样
    std::ifstream file2("/proc/stat");
    std::string line2;
    std::getline(file2, line2);
    unsigned long long us2, sy2, total2;
    std::tie(us2, sy2, total2) = parseCpuLine(line2);

    // 计算差值
    const unsigned long long total_diff = total2 - total1;
    if (total_diff == 0) return 0.0f;

    const unsigned long long us_diff = us2 - us1;
    const unsigned long long sy_diff = sy2 - sy1;

    return static_cast<float>(us_diff + sy_diff) * 100.0f / total_diff;
}

http://www.xdnf.cn/news/21673.html

相关文章:

  • 文件二进制读写和文本读写以及编码解码
  • Android 12系统静态壁纸深度定制指南
  • day2-小白学习JAVA---java第一个程序
  • 电力资源配置逐步从计划模式转向市场驱动
  • 内存函数和动态内存管理
  • leetcode刷题日记——同构字符串
  • 北京SMT贴片厂精密制造关键工艺
  • MySQL触发器和函数的详细示例
  • FairMOT算法详解
  • 【AI学习】OpenAI:《A practical guide to building agents》(中文介绍与原文)
  • 关于嵌入式系统的知识课堂(二)
  • Unity粒子特效打包后不显示
  • 【天外之物】叉乘(向量积)的行列式表示方法
  • 前端如何构建跨平台可复用的业务逻辑层(Web、App、小程序)
  • LIMS引领综合质检中心数字化变革,赋能质量强国战略
  • 前端:uniapp框架中<scroll-view>如何控制元素进行局部滚动
  • 继承的了解与学习
  • 安装多个DevEco Studio版本,如何才能保证各个版本不冲突?
  • 【ELF2学习板】Ne10进行FFT测试
  • 【T2I】DreamFuse: Adaptive Image Fusion with Diffusion Transformer
  • AOP基本概念
  • 【工具变量】地市农业播种面积及粮食产量等21个相关指标(2013-2022年)
  • 打造搜索神功:Express 路由中的关键词探查之道
  • 【linux学习】 Redhat9.5安装
  • vue+flask+CNN电影推荐系统
  • 从零基础深入学习的语音信号处理系统
  • 大模型应用_AutoGPT
  • 折扣电影票api对接详细指南,如何对接?
  • 颚式破碎机的设计
  • 【深度学习—李宏毅教程笔记】Self-attention