21xrx.com
2024-09-20 01:14:55 Friday
登录
文章检索 我的文章 写文章
C++ 如何获取内存和 CPU 使用情况?
2023-07-01 02:01:01 深夜i     --     --
C++ 内存使用情况 CPU使用情况 获取 性能监测

C++ 是一种高级编程语言,通常用于开发高性能的程序。但是,在编写程序时,了解程序使用的内存和 CPU 使用情况是非常重要的。因此,在本文中,我们将讨论如何使用 C++ 获取内存和 CPU 使用情况。

获取内存使用情况

在 C++ 中,可以使用标准库中的头文件 来获取程序的内存使用情况。该库中的函数 malloc() 和 free() 可以用于动态分配内存和释放内存。

为了获取进程的内存使用情况,我们需要使用系统特定的库。在 Windows 中,我们使用 Windows.h 库,而在 Linux 中,我们使用 sys/types.h 和 sys/sysinfo.h 库。

以下是获取 Windows 中进程内存使用情况的代码:


#include <windows.h>

PROCESS_MEMORY_COUNTERS_EX pmc;

GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));

SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;

以下是获取 Linux 中进程内存使用情况的代码:


#include <sys/types.h>

#include <sys/sysinfo.h>

struct sysinfo info;

sysinfo(&info);

unsigned long ram_used = (info.totalram - info.freeram) * info.mem_unit;

获取 CPU 使用情况

在 C++ 中,可以使用时间库的头文件 来获取程序的 CPU 使用情况。使用函数 clock() 可以获取程序已用的 CPU 时间,而使用函数 CLOCKS_PER_SEC 可以获取每秒钟的 CPU 时钟数。根据这两个值,我们可以计算出程序的 CPU 使用率。

以下是计算程序 CPU 使用率的代码:


#include <ctime>

double start_time = clock();

// do some heavy computations

double end_time = clock();

double cpu_time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;

另外,如果想获取整个系统的 CPU 使用率,我们需要使用系统特定的库。在 Windows 中,我们可以使用 Windows.h 库中的函数 GetSystemTimes(),而在 Linux 中,我们可以使用系统文件 /proc/stat。

以下是获取 Windows 中整个系统 CPU 使用率的代码:


#include <Windows.h>

FILETIME ft_idle;

FILETIME ft_kernel;

FILETIME ft_user;

GetSystemTimes(&ft_idle, &ft_kernel, &ft_user);

以下是获取 Linux 中整个系统 CPU 使用率的代码:


#include <iostream>

#include <fstream>

#include <vector>

double get_cpu_percentage() {

  std::vector<std::string> tokens;

  std::ifstream file_stat("/proc/stat");

  if (file_stat.is_open()) {

    std::string line;

    while (getline(file_stat, line)) {

      if (line.rfind("cpu", 0) == 0) {

        std::stringstream ss(line);

        std::string token;

        while (ss >> token) {

          if (token == "cpu")

            continue;

          tokens.push_back(token);

        }

        unsigned long long user = std::stoll(tokens[0]);

        unsigned long long nice = std::stoll(tokens[1]);

        unsigned long long sys = std::stoll(tokens[2]);

        unsigned long long idle = std::stoll(tokens[3]);

        unsigned long long total = user + sys + nice + idle;

        return 100.0 * (total - idle) / total;

      }

    }

  }

  return -1.0;

}

总结

在编写高性能的程序时,了解程序的内存和 CPU 使用情况非常重要。C++ 提供了获取程序内存和 CPU 使用情况的方法。这些方法不仅可以帮助我们优化程序,还可以让我们监控程序的运行情况,及时发现并解决问题。在实践中,我们可以使用这些方法获取内存和 CPU 使用情况,并在需要时做出相应的调整,以获得更好的性能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复