在C++中直接获取CPU使用率通常是依赖操作系统特性的,因为CPU时间是底层操作系统资源的一部分。不过可以基于某些API来间接获取这种数据,比如通过读取系统的信息。以下是几种常见操作系统中的获取方法:
1. Linux 系统
Linux提供了诸如 `/proc` 文件系统的方式来获取这类信息。可以通过程序读这个文件的内容。示例如下:
cpp
include
include
include
std::string readLine(std::ifstream &stream)
{
std::string result;
while(stream) {
std::string s; std::getline(stream, s);
if(!s.empty())
result.append(s + "\n");
}
return result.substr(0, result.size() 1); // Remove the last newline
}
double getCpuUsage(void)
{
double total, busy;
auto readCpuInfo = [](const std::string& fileName)
> std::vector
{
auto ss = std::ifstream(fileName);
// Read all lines
auto content = readLine(ss);
std::istringstream buf(content);
std::istream_iterator beg(buf), end;
std::vector tokens(beg, end);
ss.close();
return tokens;
};
// Read /proc/stat
const auto cpu = readCpuInfo("/proc/stat");
const std::string cpuPrefix = "cpu";
std::vector stat;
for (auto v: cpu) {
if(v.find(cpuPrefix) == 0)
stat.push_back(stod(v.substr(4)));
}
total = stat[0]+stat[1]+stat[2]+stat[3]+stat[4]+stat[5]+stat[6];
busy = total stat[3];
if (prev_total == 0)
return 0;
// Update previous values to calculate a delta.
prev_total = total;
prev_busy = busy;
const double idlePercent{prev_idle/(prev_totalprev_idle)100.0}; // Idle time
const double util_percent{ (total prev_total) > (idle prev_idle)? 100((busyprev_busy)/(totalprev_total)) : 0};
return std::max((int)(util_percent+0.5), 1);
}
// 使用前必须在函数范围内先有一个变量初始化
static double prev_total{0}, prev_idle{0};
注意这段代码只是简单的演示了计算方法,并未做很多异常检查,实际开发时应当添加必要的异常处理等。
2. Windows 系统
Windows可以通过调用 Windows API 或读取性能计数器的方法来做。一个简化的方式可以利用 Performance Counter 来实现:
cpp
include
include
include
double GetCpuPercentage()
{
LARGE_INTEGER lastTime, currentTime;
FILETIME creationTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;
SYSTEMTIME stUTC, stLocal;
DWORD lastBusy, busy, percent, lastTotal;
GetSystemTimes(&lastTime, &kernelTime, &userTime);
lastBusy = (int)(kernelTime.dwLowDateTime + kernelTime.dwHighDateTime) ;
lastTotal = ((unsigned long)kernelTime.dwLowDateTime + (unsigned long)kernelTime.dwHighDateTime + (unsigned long)userTime.dwLowDateTime + (unsigned long)userTime.dwHighDateTime) ;
Sleep(150);
GetSystemTimes(¤tTime, &kernelTime, &userTime);
busy = (int)(kernelTime.dwLowDateTime + kernelTime.dwHighDateTime) ;
unsigned long total = (unsigned long) kernelTime.dwLowDateTime + (unsigned long) kernelTime.dwHighDateTime
+ (unsigned long) userTime.dwLowDateTime + (unsigned long) userTime.dwHighDateTime ;
unsigned long diffBusy = busy lastBusy;
unsigned long diffTotal = ((unsigned long)total (unsigned long) lastTotal);
percent = (diffBusy 100LL / diffTotal);
return percent;
}
这段代码会获取当前时间和上一次调用的之间的差异,计算出总的繁忙时间比例并作为CPU利用率返回。
需要注意,无论是Linux还是Windows的例子都需要适当的错误检测和处理,并可能需要根据具体需求对代码进行相应的调整以获得更精确的结果或更好地兼容不同的使用场景。在嵌入式或其他特定环境中获取CPU利用率的具体策略还可能有所不同。
发表评论