获取当前进程cpu瞬时占用[linux][windows][c++]

linux

cpp 复制代码
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>

class ProcessCPUMonitor {
public:
    double getProcessCPUUsage() const {
        // 获取进程启动时间
        long startTime = getProcessStartTime();

        // 获取进程的 CPU 时间
        long utime, stime;
        if (getProcessCPUUsage(utime, stime)) {
            // 获取时钟滴答数的分辨率
            long clockTicks = sysconf(_SC_CLK_TCK);

            // 计算进程运行时间(秒)
            long currentTime = getCurrentTime();
            long elapsedTime = currentTime - startTime;

            // 计算 CPU 使用率
            double cpuUsage = 100.0 * ((utime + stime) / static_cast<double>(clockTicks * elapsedTime));
            return cpuUsage;
        } else {
            std::cerr << "Failed to get process CPU information.\n";
            return -1.0;
        }
    }

private:
    // 获取进程启动时间
    long getProcessStartTime() const {
        std::ifstream statFile("/proc/self/stat");
        if (!statFile.is_open()) {
            std::cerr << "Failed to open /proc/self/stat file.\n";
            return -1;
        }

        std::string line;
        std::getline(statFile, line);
        std::istringstream iss(line);

        // Skip to the start time field (22nd field)
        for (int i = 0; i < 21; ++i) {
            iss.ignore();
        }

        long startTime;
        iss >> startTime;
        return startTime;
    }

    // 获取进程的 CPU 时间(utime和stime)
    bool getProcessCPUUsage(long& utime, long& stime) const {
        std::ifstream statFile("/proc/self/stat");
        if (!statFile.is_open()) {
            std::cerr << "Failed to open /proc/self/stat file.\n";
            return false;
        }

        std::string line;
        std::getline(statFile, line);
        std::istringstream iss(line);

        // Skip to the utime field (14th field)
        for (int i = 0; i < 13; ++i) {
            iss.ignore();
        }

        iss >> utime;

        // Skip to the stime field (15th field)
        for (int i = 0; i < 1; ++i) {
            iss.ignore();
        }

        iss >> stime;

        return true;
    }

    // 获取当前时间(时钟滴答数)
    long getCurrentTime() const {
        return sysconf(_SC_CLK_TCK);
    }
};

int main() {
    ProcessCPUMonitor monitor;

    // Example: Print process CPU usage every 1 second
    for (int i = 0; i < 5; ++i) {
        sleep(1);
        std::cout << "Process CPU Usage: " << monitor.getProcessCPUUsage() << "%\n";
    }

    return 0;
}

windows

cpp 复制代码
#include <iostream>
#include <windows.h>

class ProcessCPUMonitor {
public:
    double getProcessCPUUsage() const {
        FILETIME createTime, exitTime, kernelTime, userTime;

        if (GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime)) {
            // 转换 FILETIME 结构到 64 位整数
            ULARGE_INTEGER kernel, user;
            kernel.LowPart = kernelTime.dwLowDateTime;
            kernel.HighPart = kernelTime.dwHighDateTime;

            user.LowPart = userTime.dwLowDateTime;
            user.HighPart = userTime.dwHighDateTime;

            // 计算 CPU 使用率
            double cpuUsage = 100.0 * (static_cast<double>(kernel.QuadPart + user.QuadPart) / getElapsedTime());
            return cpuUsage;
        } else {
            std::cerr << "Failed to get process CPU information.\n";
            return -1.0;
        }
    }

private:
    // 获取进程启动时间
    long long getProcessStartTime() const {
        FILETIME createTime, exitTime, kernelTime, userTime;

        if (GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime)) {
            // 转换 FILETIME 结构到 64 位整数
            ULARGE_INTEGER createTime64;
            createTime64.LowPart = createTime.dwLowDateTime;
            createTime64.HighPart = createTime.dwHighDateTime;
            return createTime64.QuadPart;
        }

        return -1;
    }

    // 获取当前时间(100纳秒为单位)
    long long getCurrentTime() const {
        FILETIME currentTime;
        GetSystemTimeAsFileTime(&currentTime);

        // 转换 FILETIME 结构到 64 位整数
        ULARGE_INTEGER currentTime64;
        currentTime64.LowPart = currentTime.dwLowDateTime;
        currentTime64.HighPart = currentTime.dwHighDateTime;

        return currentTime64.QuadPart;
    }

    // 获取经过的时间(秒为单位)
    double getElapsedTime() const {
        long long startTime = getProcessStartTime();
        long long currentTime = getCurrentTime();

        if (startTime != -1) {
            return static_cast<double>(currentTime - startTime) / 10000000.0; // 转换为秒
        }

        return -1.0;
    }
};

int main() {
    ProcessCPUMonitor monitor;

    // Example: Print process CPU usage every 1 second
    for (int i = 0; i < 5; ++i) {
        Sleep(1000);
        std::cout << "Process CPU Usage: " << monitor.getProcessCPUUsage() << "%\n";
    }

    return 0;
}
相关推荐
依然鸣1 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
allforgood1 小时前
运行容器
linux
Light_It2 小时前
Linux 内核参数 pci-stub.ids=
linux·kernel
RisunJan2 小时前
Linux命令-scriptreplay(终端会话回放)
linux·运维·chrome
库玛西3 小时前
现代 C++ 智能指针全景指南:从 RAII 思想到工业级实践
c语言·开发语言·c++·笔记·面试
spencer_tseng3 小时前
[kylin & linux] install docker
linux·docker·kylin
liulilittle3 小时前
无锁并发容器的设计与实现原理
开发语言·c++·set·map·并发·无锁·lock-free
qeen874 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
x²+(y-√³x²)²=14 小时前
Linux打包文件到Windows,文件/文件类型丢失
linux·运维·windows
世人万千丶4 小时前
去重插入与超限淘汰:ArkTS 实现鸿蒙搜索历史的 LIMIT 艺术
运维·服务器·学习·华为·harmonyos·鸿蒙