获取当前进程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;
}
相关推荐
蜀黍@猿14 分钟前
C/C++基础错题归纳
c++
wanhengidc14 分钟前
短视频运营行业该如何选择服务器?
运维·服务器
雨中rain28 分钟前
Linux -- 从抢票逻辑理解线程互斥
linux·运维·c++
-KamMinG39 分钟前
Centos7.9安装openldap+phpldapadmin+grafana配置LDAP登录最详细步骤 亲测100%能行
运维·grafana
Bessssss1 小时前
centos日志管理,xiao整理
linux·运维·centos
s_yellowfish1 小时前
Linux服务器pm2 运行chatgpt-on-wechat,搭建微信群ai机器人
linux·服务器·chatgpt
豆是浪个1 小时前
Linux(Centos 7.6)yum源配置
linux·运维·centos
vvw&1 小时前
如何在 Ubuntu 22.04 上安装 Ansible 教程
linux·运维·服务器·ubuntu·开源·ansible·devops
我一定会有钱1 小时前
【linux】NFS实验
linux·服务器
王铁柱子哟-1 小时前
解决 正在下载VS Code 服务器... 问题
运维·服务器