获取当前进程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;
}
相关推荐
筱源源5 分钟前
Kafka-linux环境部署
linux·kafka
我是谁??19 分钟前
C/C++使用AddressSanitizer检测内存错误
c语言·c++
成都古河云42 分钟前
智慧场馆:安全、节能与智能化管理的未来
大数据·运维·人工智能·安全·智慧城市
算法与编程之美44 分钟前
文件的写入与读取
linux·运维·服务器
发霉的闲鱼1 小时前
MFC 重写了listControl类(类名为A),并把双击事件的处理函数定义在A中,主窗口如何接收表格是否被双击
c++·mfc
小c君tt1 小时前
MFC中Excel的导入以及使用步骤
c++·excel·mfc
xianwu5431 小时前
反向代理模块
linux·开发语言·网络·git
xiaoxiao涛1 小时前
协程6 --- HOOK
c++·协程
Amelio_Ming1 小时前
Permissions 0755 for ‘/etc/ssh/ssh_host_rsa_key‘ are too open.问题解决
linux·运维·ssh
心灵彼岸-诗和远方1 小时前
Devops业务价值流:软件研发最佳实践
运维·产品经理·devops