21xrx.com
2025-06-30 06:11:06 Monday
登录
文章检索 我的文章 写文章
C++如何获取CPU使用率
2023-07-06 13:46:29 深夜i     31     0
C++ CPU使用率 获取

C++是一种流行的编程语言,被广泛用于开发各种应用程序,包括操作系统和其他低级系统组件。获取CPU使用率是在C++应用程序中必需的任务之一,因为它允许程序员判断系统负载,并优化程序性能。本文将介绍如何在C++中获取CPU使用率。

在C++中获取CPU使用率的方法有很多,其中最常用的方法是使用操作系统提供的函数。例如,在Windows操作系统中,可以使用Windows API函数查询CPU使用率。以下是使用QueryPerformanceCounter函数计算CPU使用率的示例代码:

#include <Windows.h>
#include <cstdio>
double GetCpuUsage()
{
  FILETIME idleTime, kernelTime, userTime;
  ULARGE_INTEGER t1, t2;
  double cpuUsage = 0;
  
  if (GetSystemTimes(&idleTime, &kernelTime, &userTime))
  {
    memcpy(&t1, &idleTime, sizeof(FILETIME));
    memcpy(&t2, &userTime, sizeof(FILETIME));
    cpuUsage = (1 - ((double)(t2.QuadPart - t1.QuadPart) / (double)(kernelTime.QuadPart + userTime.QuadPart - t1.QuadPart))) * 100;
  }
  
  return cpuUsage;
}
int main()
{
  double cpuUsage = GetCpuUsage();
  printf("CPU Usage: %.2f %%\n", cpuUsage);
  return 0;
}

代码首先调用GetSystemTimes函数获取当前的系统时间,包括空闲时间、内核时间和用户时间。由于文件时间结构采用64位整数表示,因此需要将其转换为ULARGE_INTEGER结构。然后,利用计算公式计算CPU使用率,并返回结果。

在Linux中,使用proc文件系统可以轻松地获取CPU使用率。proc文件夹包含许多系统信息,包括和CPU使用率相关的信息。以下是使用proc文件系统计算CPU使用率的示例代码:

#include <cstdio>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstring>
int main()
{
  std::ifstream file("/proc/stat");
  unsigned long long total, work;
  unsigned long long total1 = 0, work1 = 0;
  unsigned long long total2 = 0, work2 = 0;
  std::string cpu;
  file >> cpu >> total >> work;
  total1 += total, work1 += work;
  while (file >> cpu >> total >> work) {
    total1 += total, work1 += work;
    if (cpu == "cpu")
      total2 = total1
  }
  sleep(1);
  file.seekg(0, std::ios::beg);
  file.clear();
  file >> cpu >> total >> work;
  total1 = 0, work1 = 0;
  total1 += total, work1 += work;
  while (file >> cpu >> total >> work) {
    total1 += total, work1 += work;
    if (cpu == "cpu")
      total2 = total1
  }
  double cpuUsage = double(work2 - work1) / double(total2 - total1) * 100;
  std::printf("CPU Usage: %.2f %%\n", cpuUsage);
  return 0;
}

代码打开/proc/stat文件并读取其中的系统信息。特别是,在第一次循环中,将信息存储在total1和work1变量中,并通过统计第一个CPU信息的总时间,计算出total2和work2变量的值。通过休眠1s后再读取/proc/stat文件,再次计算total1、total2、work1和work2,并计算CPU使用率。

通过以上示例,可以看到获取CPU使用率在C++应用程序中是一项重要的任务。通过操作系统提供的函数和系统信息,可以轻松地获取CPU使用率并进行性能优化。

  
  

评论区