C++获取windows和linux的cpu占用率

代码

cpuload.h

#pragma once

#include <iostream>
#include <vector>

#ifndef WIN32

class CPUData {
public:
  void ReadData(const std::string &line);

  std::size_t GetActiveTime() const;
  std::size_t GetIdleTime() const;
  std::size_t GetStateTime(unsigned int state) const;
  std::size_t GetTotalTime() const;

  const std::string &GetLabel() const;

public:
  static bool IsDataCPUStats(const std::string &line);

public:
  enum CPUStates {
    S_USER = 0,
    S_NICE,
    S_SYSTEM,
    S_IDLE,
    S_IOWAIT,
    S_IRQ,
    S_SOFTIRQ,
    S_STEAL,
    S_GUEST,
    S_GUEST_NICE,

    NUM_CPU_STATES
  };

private:
  static const std::string STR_CPU;
  static const std::string STR_TOT;

  static const std::size_t LEN_STR_CPU;

private:
  std::string mLabel;
  std::size_t mTimes[NUM_CPU_STATES];
};

inline std::size_t CPUData::GetActiveTime() const {
  return mTimes[S_USER] + mTimes[S_NICE] + mTimes[S_SYSTEM] + mTimes[S_IRQ] +
         mTimes[S_SOFTIRQ] + mTimes[S_STEAL] + mTimes[S_GUEST] +
         mTimes[S_GUEST_NICE];
}

inline std::size_t CPUData::GetIdleTime() const {
  return mTimes[S_IDLE] + mTimes[S_IOWAIT];
}

inline std::size_t CPUData::GetStateTime(unsigned int state) const {
  if (state < NUM_CPU_STATES)
    return mTimes[state];
  else
    return 0;
}

inline std::size_t CPUData::GetTotalTime() const {
  return mTimes[S_USER] + mTimes[S_NICE] + mTimes[S_SYSTEM] + mTimes[S_IDLE] +
         mTimes[S_IOWAIT] + mTimes[S_IRQ] + mTimes[S_SOFTIRQ] +
         mTimes[S_STEAL] + mTimes[S_GUEST] + mTimes[S_GUEST_NICE];
}

inline const std::string &CPUData::GetLabel() const { return mLabel; }

inline bool CPUData::IsDataCPUStats(const std::string &line) {
  return (!line.compare(0, LEN_STR_CPU, STR_CPU));
}

class CPUSnapshot {
public:
  CPUSnapshot();

  std::size_t GetNumEntries() const;

  const char *GetLabelTotal() const;
  const char *GetLabel(unsigned int cpu) const;

  std::size_t GetActiveTimeTotal() const;
  std::size_t GetActiveTime(unsigned int cpu) const;

  std::size_t GetIdleTimeTotal() const;
  std::size_t GetIdleTime(unsigned int cpu) const;

  std::size_t GetStateTimeTotal(unsigned int state) const;
  std::size_t GetStateTime(unsigned int state, unsigned int cpu) const;

  std::size_t GetTotalTimeTotal() const;
  std::size_t GetTotalTime(unsigned int cpu) const;

private:
  static const int INDEX_TOT;

private:
  std::vector<CPUData> mEntries;
};

inline std::size_t CPUSnapshot::GetNumEntries() const {
  return mEntries.size() - 1;
}

inline const char *CPUSnapshot::GetLabelTotal() const {
  return mEntries[INDEX_TOT].GetLabel().c_str();
}

inline const char *CPUSnapshot::GetLabel(unsigned int cpu) const {
  // skip total
  ++cpu;

  if (cpu < mEntries.size())
    return mEntries[cpu].GetLabel().c_str();
  else
    return NULL;
}

inline std::size_t CPUSnapshot::GetActiveTimeTotal() const {
  return mEntries[INDEX_TOT].GetActiveTime();
}

inline std::size_t CPUSnapshot::GetActiveTime(unsigned int cpu) const {
  // skip total
  ++cpu;

  if (cpu < mEntries.size())
    return mEntries[cpu].GetActiveTime();
  else
    return 0;
}

inline std::size_t CPUSnapshot::GetIdleTimeTotal() const {
  return mEntries[INDEX_TOT].GetIdleTime();
}

inline std::size_t CPUSnapshot::GetIdleTime(unsigned int cpu) const {
  // skip total
  ++cpu;

  if (cpu < mEntries.size())
    return mEntries[cpu].GetIdleTime();
  else
    return 0;
}

inline std::size_t CPUSnapshot::GetStateTimeTotal(unsigned int state) const {
  return mEntries[INDEX_TOT].GetStateTime(state);
}

inline std::size_t CPUSnapshot::GetStateTime(unsigned int state,
                                             unsigned int cpu) const {
  // skip total
  ++cpu;

  if (cpu < mEntries.size())
    return mEntries[cpu].GetStateTime(state);
  else
    return 0;
}

inline std::size_t CPUSnapshot::GetTotalTimeTotal() const {
  return mEntries[INDEX_TOT].GetTotalTime();
}

inline std::size_t CPUSnapshot::GetTotalTime(unsigned int cpu) const {
  // skip total
  ++cpu;

  if (cpu < mEntries.size())
    return mEntries[cpu].GetTotalTime();
  else
    return 0;
}
#endif

class LoadMnger {
public:
  ~LoadMnger();

  static LoadMnger *instance();

  double GetCpuUsage();

private:
  LoadMnger();
  static LoadMnger *m_instance;

#ifdef WIN32
  unsigned long long m_ullLastTime;
  unsigned long long m_ullLastIdleTime;
#else
  size_t m_ullLastTime;
  size_t m_ullLastIdleTime;
#endif
};

cpuload.cpp

#include "LoadManager.h"

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#ifdef WIN32
#include <windows.h>
#else

using namespace std;

const std::string CPUData::STR_CPU("cpu");
const std::string CPUData::STR_TOT("tot");
const std::size_t CPUData::LEN_STR_CPU = 3;
const int CPUSnapshot::INDEX_TOT = 0;
#endif

LoadMnger *LoadMnger::m_instance = NULL;

LoadMnger::LoadMnger() {
	GetCpuUsage();
}

LoadMnger::~LoadMnger() {}

LoadMnger *LoadMnger::instance() {
  if (!m_instance)
    m_instance = new LoadMnger();
  return m_instance;
}

#ifdef WIN32
unsigned long long __FileTime2Utc(const FILETIME &ft) {
  LARGE_INTEGER li;
  li.LowPart = ft.dwLowDateTime;
  li.HighPart = ft.dwHighDateTime;
  return li.QuadPart;
}

double LoadMnger::GetCpuUsage() {
  FILETIME idleTime, kernelTime, userTime;
  if (!GetSystemTimes(&idleTime, &kernelTime, &userTime)) {
    printf("GetSystemTimes", GetLastError());
    return -1;
  }
  unsigned long long _time =
                         __FileTime2Utc(kernelTime) + __FileTime2Utc(userTime),
                     _idle_time = __FileTime2Utc(idleTime);
  if (!m_ullLastTime || !m_ullLastIdleTime) {
    m_ullLastIdleTime = _idle_time;
    m_ullLastTime = _time;
    return -1;
  }
  unsigned long long idle = _idle_time - m_ullLastIdleTime,
                     usage = _time - m_ullLastTime;
  m_ullLastIdleTime = _idle_time;
  m_ullLastTime = _time;
  if (!usage)
    return -1;
  return (usage - idle) * 100.0 / usage;
}
#else
double LoadMnger::GetCpuUsage() {
  CPUSnapshot Csp;

  size_t curacTime = Csp.GetActiveTimeTotal();
  size_t curidlTIme = Csp.GetIdleTimeTotal();
  const float ACTIVE_TIME = curacTime - m_ullLastTime;
  const float IDLE_TIME = curidlTIme - m_ullLastIdleTime;
  const float TOTAL_TIME = ACTIVE_TIME + IDLE_TIME;

  m_ullLastTime = curacTime;
  m_ullLastIdleTime = curidlTIme;
  return 100.f * ACTIVE_TIME / TOTAL_TIME;
}

// == PUBLIC FUNCTIONS ==
CPUSnapshot::CPUSnapshot() {
  std::ifstream fileStat("/proc/stat");

  std::string line;

  while (std::getline(fileStat, line)) {
    // cpu stats line found
    if (CPUData::IsDataCPUStats(line)) {
      // store entry
      mEntries.push_back(CPUData());
      CPUData &entry = mEntries.back();

      entry.ReadData(line);
    }
  }
}

// == PUBLIC FUNCTIONS ==

void CPUData::ReadData(const std::string &line) {
  std::istringstream ss(line);

  // read cpu label
  ss >> mLabel;

  // remove "cpu" from the label when it's a processor number
  if (mLabel.size() > LEN_STR_CPU)
    mLabel.erase(0, LEN_STR_CPU);
  // replace "cpu" with "tot" when it's total values
  else
    mLabel = STR_TOT;

  // read times
  for (int i = 0; i < NUM_CPU_STATES; ++i) {
    ss >> mTimes[i];
  }
}

#endif

main.cpp
#include "LoadManager.h"

#include <iostream>
#include <string>

#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

using namespace std;

int main() {
  LoadMnger *mng = LoadMnger::instance();
  while (1) {
    //如果时间间隔太短会计算失败,具体可以看GetCpuUsage()中GetSystemTimes获取的结果
#ifdef WIN32
    Sleep(1000);
#else
    sleep(1);
#endif
    double usage = mng->GetCpuUsage();
    cout << "main:  " << usage << endl;
  }
  return 0;
}

代码是参考大佬的代码合并、修改而来,如有侵权,请私信删除。

部分源码来自:
https://github.com/vivaladav/cpu-stat
https://github.com/mewiteor/MonitorBar

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpUploader4全面升级了文件IO组件。新的IO组件在处理磁盘中的文件时,将不必再对文件执行I/O操作,这意味着在对文件进行处理时将不必再为文件申请并分配缓存,所有的文件缓存操作均由系统直接管理,由于取消了将文件数据加载到内存、数据从内存到文件的回写以及释放内存块等步骤,使得HttpUploader4在处理TB级数据时能够拥有闪电般的速度。 新的IO组件赋予了HttpUploader4更强的大数据处理能力。现在HttpUploader4在对GB级文件进行MD5校验时速度提高了4倍。同时CPU占用率更低。 HttpUploader4更加注重对硬盘的保护,在HttpUploader4中不再直接对文件进行I/O操作,而是在内存中对文件进行操作,所以不仅极大的减少了对硬盘的读写次数,同时速度却变的更快了。 借助于HttpUploader4企业能够帮助用户更加轻松的处理工作中的文件,让用户与用户之间的沟通更加的高效。从根本上提高企业竞争力。 考虑到不同的企业使用的开发平台不同,我们已经为企业开发人员提供了完整的与数据库相结合的示例(ASP.NET,JSP,PHP)。开发人员能够非常容易的在自已的系统中实现断点续传功能。 产品特点如下: 1. 为TB级文件提供稳定传输功能。 2. 优化MD5组件,文件扫描速度提升70%。 3. 保护磁盘,上传超大文件时,磁盘IO次数降低50%。 4. 采用全新设计IO组件,上传任意文件大小时始终占用128KB内存。 5. 支持文件及文件夹拖拽上传功能。 6. 支持文件批量上传。 7. 支持文件夹上传。 8. 基于标准HTTP协议。 9. 免费提供JavaScript SDK包,方便您将插件快速集成到已有网站中。 支持语言:PHP,JSP,ASP,ASP.NET(C#),ASP.NET(VB),C++,VC,VC.NET,VB,VB.NET,C#,C#.NET,Delphi,C++Builder 支持平台:Visual Studio 6.0/2002/2003/2005/2008/2010,C++ Builder 6.0/2009/2010,Delphi 7/2009,Visual Basic 6.0/2008,MyEclipse8.x 支持脚本:JavaScript,VBScript 支持服务器:Windows NT,Windows 2003,Windows XP,Windows Vista,Windows 7,Linux,Unix 支持浏览器:IE6,IE7,IE8,360安全浏览器,QQ浏览器,搜狐浏览器,Maxthon(遨游)浏览器1.X,Maxthon(傲游)浏览器2.x 支持文件大小:2G~8EB(1EB=102PB,1PB=1024TB,1TB=1024GB) 支持文件类型:任意类型 版权所有 2009-2012 武汉命运科技有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webplug/http-uploader3/index.aspx 在线演示:http://www.ncmem.com/products/http-uploader3/demo/index.html 产品介绍:http://www.cnblogs.com/xproer/archive/2012/05/29/2523757.html 开发文档-ASP:http://www.cnblogs.com/xproer/archive/2012/02/17/2355458.html 开发文档-PHP:http://www.cnblogs.com/xproer/archive/2012/02/17/2355467.html 开发文档-JSP:http://www.cnblogs.com/xproer/archive/2012/02/17/2355462.html 开发文档-ASP.NET:http://www.cnblogs.com/xproer/archive/2012/02/17/2355469.html 升级日志:http://www.cnblogs.com/xproer/archive/2012/02/17/2355449.html 示例下载:http://www.ncmem.com/download/HttpUploader4-demo.rar 文档下载:http://www.ncmem.com/download/HttpUploader4-doc.rar 镜像下载(DBank):cab安装包,开发文档 镜像下载(JSP):cab安装包,开发文档,ASP.NET-ACCESS示例,JSP-ACCESS示例(GB2312),JSP-ACCESS示例(UTF-8),JSP-Sql2005示例(UTF-8),JSP-MySQL示例(UTF-8) 镜像下载(PHP):MySQL示例(UTF-8) 问题反馈:http://www.ncmem.com/blog/guestbook.asp 数字证书补丁:http://www.ncmem.com/download/rootsupd.rar VC运行库:http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=29 联系信箱:[email protected] 联系QQ:1085617561 技术QQ:1269085759
1.项目代码均经过功能验证ok,确保稳定可靠运行。欢迎下载体验!下载完使用问题请私信沟通。 2.主要针对各个计算机相关专业,包括计算机科学、信息安全、数据科学与大数据技术、人工智能、通信、物联网等领域的在校学生、专业教师、企业员工。 3.项目具有丰富的拓展空间,不仅可作为入门进阶,也可直接作为毕设、课程设计、大作业、初期项目立项演示等用途。 4.当然也鼓励大家基于此进行二次开发。在使用过程中,如有问题或建议,请及时沟通。 5.期待你能在项目中找到乐趣和灵感,也欢迎你的分享和反馈! 【资源说明】 基于RK3588部署YOLOv5多线程推理C++源码+项目说明(支持4路视频AI分析).zip 此项目为c++实现yolo5的batch多线程推理 实现4路摄像头的batch=4的推理 # 使用说明 模型转换 * yolov5工程下export.py转换onnx,直接转,切忌修改batch_size * 参考网上方法,rknn-toolkit2进行onnx转rknn,需要修改./rknn-toolkit2/examples/onnx/test.py为本工程test.py 演示 * 系统需安装有**OpenCV**,如果需要读取AHD摄像头还需要安装**gstreamer** * 运行build-linux_RK3588.sh * 可切换至root用户运行performance.sh定频提高性能和稳定性 * 编译完成后进入install运行命令./rknn_yolov5_demo **模型所在路径** 部署应用 * 修改include/rknnPool.hpp中的rknn_lite类 * 修改inclue/rknnPool.hpp中的rknnPool类的构造函数 # 多线程模型帧率测试 * 使用performance.sh进行CPU/NPU定频尽量减少误差 * 设置线程数为8,batch_size=4,读取USB摄像头视频流测试,平均处理速度15.8FPS*4,八核CPU占用率约500%,三核NPU平均占用率75% ![示例](./view.png) # 补充 * 异常处理尚未完善, 目前仅支持rk3588/rk3588s下的运行
HttpUploader4全面升级了文件IO组件。新的IO组件在处理磁盘中的文件时,将不必再对文件执行I/O操作,这意味着在对文件进行处理时将不必再为文件申请并分配缓存,所有的文件缓存操作均由系统直接管理,由于取消了将文件数据加载到内存、数据从内存到文件的回写以及释放内存块等步骤,使得HttpUploader4在处理TB级数据时能够拥有闪电般的速度。 新的IO组件赋予了HttpUploader4更强的大数据处理能力。现在HttpUploader4在对GB级文件进行MD5校验时速度提高了4倍。同时CPU占用率更低。 HttpUploader4更加注重对硬盘的保护,在HttpUploader4中不再直接对文件进行I/O操作,而是在内存中对文件进行操作,所以不仅极大的减少了对硬盘的读写次数,同时速度却变的更快了。 借助于HttpUploader4企业能够帮助用户更加轻松的处理工作中的文件,让用户与用户之间的沟通更加的高效。从根本上提高企业竞争力。 考虑到不同的企业使用的开发平台不同,我们已经为企业开发人员提供了完整的与数据库相结合的示例(ASP.NET,JSP,PHP)。开发人员能够非常容易的在自已的系统中实现断点续传功能。 产品特点如下: 1. 为TB级文件提供稳定传输功能。 2. 优化MD5组件,文件扫描速度提升70%。 3. 保护磁盘,上传超大文件时,磁盘IO次数降低50%。 4. 采用全新设计IO组件,上传任意文件大小时始终占用128KB内存。 5. 支持文件及文件夹拖拽上传功能。 6. 支持文件批量上传。 7. 支持文件夹上传。 8. 基于标准HTTP协议。 9. 免费提供JavaScript SDK包,方便您将插件快速集成到已有网站中。 支持语言:PHP,JSP,ASP,ASP.NET(C#),ASP.NET(VB),C++,VC,VC.NET,VB,VB.NET,C#,C#.NET,Delphi,C++Builder 支持平台:Visual Studio 6.0/2002/2003/2005/2008/2010,C++ Builder 6.0/2009/2010,Delphi 7/2009,Visual Basic 6.0/2008,MyEclipse8.x 支持脚本:JavaScript,VBScript 支持服务器:Windows NT,Windows 2003,Windows XP,Windows Vista,Windows 7,Linux,Unix 支持浏览器:IE6,IE7,IE8,360安全浏览器,QQ浏览器,搜狐浏览器,Maxthon(遨游)浏览器1.X,Maxthon(傲游)浏览器2.x 支持文件大小:2G~8EB(1EB=102PB,1PB=1024TB,1TB=1024GB) 支持文件类型:任意类型 版权所有 2009-2012 武汉命运科技有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webplug/http-uploader3/index.aspx 在线演示:http://www.ncmem.com/products/http-uploader3/demo/index.html 产品介绍:http://www.cnblogs.com/xproer/archive/2012/05/29/2523757.html 开发文档-ASP:http://www.cnblogs.com/xproer/archive/2012/02/17/2355458.html 开发文档-PHP:http://www.cnblogs.com/xproer/archive/2012/02/17/2355467.html 开发文档-JSP:http://www.cnblogs.com/xproer/archive/2012/02/17/2355462.html 开发文档-ASP.NET:http://www.cnblogs.com/xproer/archive/2012/02/17/2355469.html 升级日志:http://www.cnblogs.com/xproer/archive/2012/02/17/2355449.html 资源下载:cab安装包,开发文档, 示例下载(ASP.NET):ASP.NET-ACCESS示例 示例下载(JSP):JSP-ACCESS示例(GB2312),JSP-ACCESS示例(UTF-8),JSP-Sql2005示例(UTF-8),JSP-MySQL示例(UTF-8) 示例下载(PHP):MySQL示例(UTF-8) 问题反馈:http://www.ncmem.com/bbs/showforum-4.aspx VC运行库:http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=29 联系信箱:[email protected] 联系QQ:1085617561

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值