获取当前进程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;
}
相关推荐
之歆4 小时前
Linux文件系统与FHS详解
linux·文件系统
China_Yanhy6 小时前
转型AI运维工程师·Day 7:构建“数据飞轮” —— 每一句对话都是资产
运维·人工智能·状态模式
Mr_WangAndy6 小时前
C++数据结构与算法_线性表_数组_概念动态数组,刷题
c++·二分查找·数组刷题·数组字符串逆序·零移动·有序数组的平方
阿猿收手吧!6 小时前
【C++】jthread:优雅终止线程新方案
开发语言·c++
zl_dfq6 小时前
Linux 之 【多线程】(死锁、同步与竞态条件、条件变量、pthread_cond_xxx、POSIX信号量、sem_xxx)
linux
学Linux的语莫6 小时前
k8s常用命令
linux·容器·kubernetes
openKylin6 小时前
《2025年度OpenAtom openKylin社区全景案例集》正式发布
linux
CS_Zero6 小时前
Ubuntu安装Claude Code
linux·ubuntu·ai编程·claude
十五年专注C++开发7 小时前
C++中各平台表示Debug的宏
开发语言·c++·debug
A星空1237 小时前
三、Kconfig介绍以及制作menuconfig界面
linux·运维·服务器