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

发布时间:2023年12月28日

linux

#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

#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;
}

文章来源:https://blog.csdn.net/wo871427008/article/details/135258082
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。