C++ 如何从进程内部确定 CPU 和内存消耗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/63166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:35:35  来源:igfitidea点击:

How to determine CPU and memory consumption from inside a process?

c++cmemorycpu

提问by Lanzelot

I once had the task of determining the following performance parameters from inside a running application:

我曾经负责从正在运行的应用程序内部确定以下性能参数:

  • Total virtual memory available
  • Virtual memory currently used
  • Virtual memory currently used by my process
  • Total RAM available
  • RAM currently used
  • RAM currently used by my process
  • % CPU currently used
  • % CPU currently used by my process
  • 可用虚拟内存总量
  • 当前使用的虚拟内存
  • 我的进程当前使用的虚拟内存
  • 可用内存总量
  • 当前使用的内存
  • 我的进程当前使用的 RAM
  • 当前使用的 CPU 百分比
  • 我的进程当前使用的 CPU 百分比

The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.

代码必须在 Windows 和 Linux 上运行。尽管这似乎是一项标准任务,但在手册(WIN32 API、GNU 文档)以及 Internet 上找到必要的信息花了我几天时间,因为关于这个主题的信息太多不完整/不正确/过时在那里发现。

In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.

为了避免其他人遇到同样的麻烦,我认为最好将所有分散的信息以及我通过反复试验发现的信息收集到一个地方。

回答by Lanzelot

Windows

视窗

Some of the above values are easily available from the appropriate WIN32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)

上面的一些值可以很容易地从适当的 WIN32 API 中获得,为了完整起见,我只是在这里列出它们。然而,其他的需要从 Performance Data Helper 库 (PDH) 中获取,这有点“不直观”并且需要大量痛苦的反复试验才能开始工作。(至少我花了很长时间,也许我只是有点愚蠢......)

Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!

注意:为了清楚起见,以下代码中省略了所有错误检查。请检查返回代码...!



  • Total Virtual Memory:

    #include "windows.h"
    
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    

    Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.

  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

    DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    
  • Virtual Memory currently used by current process:

    #include "windows.h"
    #include "psapi.h"
    
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
    
  • 总虚拟内存:

    #include "windows.h"
    
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    

    注意:名称“TotalPageFile”在这里有点误导。实际上,此参数给出了“虚拟内存大小”,即交换文件的大小加上已安装的 RAM。

  • 当前使用的虚拟内存:

    与“总虚拟内存”中的代码相同,然后

    DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    
  • 当前进程当前使用的虚拟内存:

    #include "windows.h"
    #include "psapi.h"
    
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
    





  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then
    
    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
    
  • Physical Memory currently used by current process:

    Same code as in "Virtual Memory currently used by current process" and then

    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
    
  • 总物理内存 (RAM):

    与“总虚拟内存”中的代码相同,然后

    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    
  • 当前使用的物理内存:

    Same code as in "Total Virtual Memory" and then
    
    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
    
  • 当前进程当前使用的物理内存:

    与“当前进程当前使用的虚拟内存”中的代码相同,然后

    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
    





  • CPU currently used:

    #include "TCHAR.h"
    #include "pdh.h"
    
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuTotal;
    
    void init(){
        PdhOpenQuery(NULL, NULL, &cpuQuery);
        // You can also use L"\Processor(*)\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
        PdhAddEnglishCounter(cpuQuery, L"\Processor(_Total)\% Processor Time", NULL, &cpuTotal);
        PdhCollectQueryData(cpuQuery);
    }
    
    double getCurrentValue(){
        PDH_FMT_COUNTERVALUE counterVal;
    
        PdhCollectQueryData(cpuQuery);
        PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
        return counterVal.doubleValue;
    }
    
  • CPU currently used by current process:

    #include "windows.h"
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    static HANDLE self;
    
    void init(){
        SYSTEM_INFO sysInfo;
        FILETIME ftime, fsys, fuser;
    
        GetSystemInfo(&sysInfo);
        numProcessors = sysInfo.dwNumberOfProcessors;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&lastCPU, &ftime, sizeof(FILETIME));
    
        self = GetCurrentProcess();
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
        memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
    }
    
    double getCurrentValue(){
        FILETIME ftime, fsys, fuser;
        ULARGE_INTEGER now, sys, user;
        double percent;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&now, &ftime, sizeof(FILETIME));
    
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&sys, &fsys, sizeof(FILETIME));
        memcpy(&user, &fuser, sizeof(FILETIME));
        percent = (sys.QuadPart - lastSysCPU.QuadPart) +
            (user.QuadPart - lastUserCPU.QuadPart);
        percent /= (now.QuadPart - lastCPU.QuadPart);
        percent /= numProcessors;
        lastCPU = now;
        lastUserCPU = user;
        lastSysCPU = sys;
    
        return percent * 100;
    }
    
  • 当前使用的CPU:

    #include "TCHAR.h"
    #include "pdh.h"
    
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuTotal;
    
    void init(){
        PdhOpenQuery(NULL, NULL, &cpuQuery);
        // You can also use L"\Processor(*)\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
        PdhAddEnglishCounter(cpuQuery, L"\Processor(_Total)\% Processor Time", NULL, &cpuTotal);
        PdhCollectQueryData(cpuQuery);
    }
    
    double getCurrentValue(){
        PDH_FMT_COUNTERVALUE counterVal;
    
        PdhCollectQueryData(cpuQuery);
        PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
        return counterVal.doubleValue;
    }
    
  • 当前进程当前使用的CPU:

    #include "windows.h"
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    static HANDLE self;
    
    void init(){
        SYSTEM_INFO sysInfo;
        FILETIME ftime, fsys, fuser;
    
        GetSystemInfo(&sysInfo);
        numProcessors = sysInfo.dwNumberOfProcessors;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&lastCPU, &ftime, sizeof(FILETIME));
    
        self = GetCurrentProcess();
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
        memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
    }
    
    double getCurrentValue(){
        FILETIME ftime, fsys, fuser;
        ULARGE_INTEGER now, sys, user;
        double percent;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&now, &ftime, sizeof(FILETIME));
    
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&sys, &fsys, sizeof(FILETIME));
        memcpy(&user, &fuser, sizeof(FILETIME));
        percent = (sys.QuadPart - lastSysCPU.QuadPart) +
            (user.QuadPart - lastUserCPU.QuadPart);
        percent /= (now.QuadPart - lastCPU.QuadPart);
        percent /= numProcessors;
        lastCPU = now;
        lastUserCPU = user;
        lastSysCPU = sys;
    
        return percent * 100;
    }
    


Linux

Linux

On Linux the choice that seemed obvious at first was to use the POSIX APIs like getrusage()etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?

在 Linux 上,一开始似乎很明显的选择是使用 POSIX API 等getrusage()。我花了一些时间试图让它工作,但从未得到有意义的值。当我最终检查内核源代码本身时,我发现这些 API 显然还没有从 Linux 内核 2.6 开始完全实现!?

In the end I got all values via a combination of reading the pseudo-filesystem /procand kernel calls.

最后,我通过读取伪文件系统/proc和内核调用的组合获得了所有值。

  • Total Virtual Memory:

    #include "sys/types.h"
    #include "sys/sysinfo.h"
    
    struct sysinfo memInfo;
    
    sysinfo (&memInfo);
    long long totalVirtualMem = memInfo.totalram;
    //Add other values in next statement to avoid int overflow on right hand side...
    totalVirtualMem += memInfo.totalswap;
    totalVirtualMem *= memInfo.mem_unit;
    
  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
    //Add other values in next statement to avoid int overflow on right hand side...
    virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
    virtualMemUsed *= memInfo.mem_unit;
    
  • Virtual Memory currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    int parseLine(char* line){
        // This assumes that a digit will be found and the line ends in " Kb".
        int i = strlen(line);
        const char* p = line;
        while (*p <'0' || *p > '9') p++;
        line[i-3] = '
    #include "sys/types.h"
    #include "sys/sysinfo.h"
    
    struct sysinfo memInfo;
    
    sysinfo (&memInfo);
    long long totalVirtualMem = memInfo.totalram;
    //Add other values in next statement to avoid int overflow on right hand side...
    totalVirtualMem += memInfo.totalswap;
    totalVirtualMem *= memInfo.mem_unit;
    
    '; i = atoi(p); return i; } int getValue(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmSize:", 7) == 0){ result = parseLine(line); break; } } fclose(file); return result; }
  • 总虚拟内存:

    long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
    //Add other values in next statement to avoid int overflow on right hand side...
    virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
    virtualMemUsed *= memInfo.mem_unit;
    
  • 当前使用的虚拟内存:

    与“总虚拟内存”中的代码相同,然后

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    int parseLine(char* line){
        // This assumes that a digit will be found and the line ends in " Kb".
        int i = strlen(line);
        const char* p = line;
        while (*p <'0' || *p > '9') p++;
        line[i-3] = '
    long long totalPhysMem = memInfo.totalram;
    //Multiply in next statement to avoid int overflow on right hand side...
    totalPhysMem *= memInfo.mem_unit;
    
    '; i = atoi(p); return i; } int getValue(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmSize:", 7) == 0){ result = parseLine(line); break; } } fclose(file); return result; }
  • 当前进程当前使用的虚拟内存:

    long long physMemUsed = memInfo.totalram - memInfo.freeram;
    //Multiply in next statement to avoid int overflow on right hand side...
    physMemUsed *= memInfo.mem_unit;
    





  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmRSS:", 6) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long totalPhysMem = memInfo.totalram;
    //Multiply in next statement to avoid int overflow on right hand side...
    totalPhysMem *= memInfo.mem_unit;
    
  • Physical Memory currently used by current process:

    Change getValue() in "Virtual Memory currently used by current process" as follows:

    long long physMemUsed = memInfo.totalram - memInfo.freeram;
    //Multiply in next statement to avoid int overflow on right hand side...
    physMemUsed *= memInfo.mem_unit;
    

  • 总物理内存 (RAM):

    与“总虚拟内存”中的代码相同,然后

    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmRSS:", 6) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    
  • 当前使用的物理内存:

    与“总虚拟内存”中的代码相同,然后

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
    
    void init(){
        FILE* file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
            &lastTotalSys, &lastTotalIdle);
        fclose(file);
    }
    
    double getCurrentValue(){
        double percent;
        FILE* file;
        unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
    
        file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
            &totalSys, &totalIdle);
        fclose(file);
    
        if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
            totalSys < lastTotalSys || totalIdle < lastTotalIdle){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
                (totalSys - lastTotalSys);
            percent = total;
            total += (totalIdle - lastTotalIdle);
            percent /= total;
            percent *= 100;
        }
    
        lastTotalUser = totalUser;
        lastTotalUserLow = totalUserLow;
        lastTotalSys = totalSys;
        lastTotalIdle = totalIdle;
    
        return percent;
    }
    
  • 当前进程当前使用的物理内存:

    更改“当前进程当前使用的虚拟内存”中的 getValue() 如下:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    #include "sys/times.h"
    #include "sys/vtimes.h"
    
    static clock_t lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    
    void init(){
        FILE* file;
        struct tms timeSample;
        char line[128];
    
        lastCPU = times(&timeSample);
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        file = fopen("/proc/cpuinfo", "r");
        numProcessors = 0;
        while(fgets(line, 128, file) != NULL){
            if (strncmp(line, "processor", 9) == 0) numProcessors++;
        }
        fclose(file);
    }
    
    double getCurrentValue(){
        struct tms timeSample;
        clock_t now;
        double percent;
    
        now = times(&timeSample);
        if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
            timeSample.tms_utime < lastUserCPU){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            percent = (timeSample.tms_stime - lastSysCPU) +
                (timeSample.tms_utime - lastUserCPU);
            percent /= (now - lastCPU);
            percent /= numProcessors;
            percent *= 100;
        }
        lastCPU = now;
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        return percent;
    }
    





  • CPU currently used:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
    
    void init(){
        FILE* file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
            &lastTotalSys, &lastTotalIdle);
        fclose(file);
    }
    
    double getCurrentValue(){
        double percent;
        FILE* file;
        unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
    
        file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
            &totalSys, &totalIdle);
        fclose(file);
    
        if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
            totalSys < lastTotalSys || totalIdle < lastTotalIdle){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
                (totalSys - lastTotalSys);
            percent = total;
            total += (totalIdle - lastTotalIdle);
            percent /= total;
            percent *= 100;
        }
    
        lastTotalUser = totalUser;
        lastTotalUserLow = totalUserLow;
        lastTotalSys = totalSys;
        lastTotalIdle = totalIdle;
    
        return percent;
    }
    
  • CPU currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    #include "sys/times.h"
    #include "sys/vtimes.h"
    
    static clock_t lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    
    void init(){
        FILE* file;
        struct tms timeSample;
        char line[128];
    
        lastCPU = times(&timeSample);
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        file = fopen("/proc/cpuinfo", "r");
        numProcessors = 0;
        while(fgets(line, 128, file) != NULL){
            if (strncmp(line, "processor", 9) == 0) numProcessors++;
        }
        fclose(file);
    }
    
    double getCurrentValue(){
        struct tms timeSample;
        clock_t now;
        double percent;
    
        now = times(&timeSample);
        if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
            timeSample.tms_utime < lastUserCPU){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            percent = (timeSample.tms_stime - lastSysCPU) +
                (timeSample.tms_utime - lastUserCPU);
            percent /= (now - lastCPU);
            percent /= numProcessors;
            percent *= 100;
        }
        lastCPU = now;
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        return percent;
    }
    
  • 当前使用的CPU:

    struct statfs stats;
    if (0 == statfs("/", &stats))
    {
        myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;
    }
    
  • 当前进程当前使用的CPU:

    sysctl -n vm.swapusage
    vm.swapusage: total = 3072.00M  used = 2511.78M  free = 560.22M  (encrypted)
    


TODO: Other Platforms

TODO:其他平台

I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by getrusage()and similar functions? If someone with Unix know-how could edit this answer and fill in the details?!

我认为,除了读取 /proc 伪文件系统的部分之外,一些 Linux 代码也适用于 Unix。也许在 Unix 上这些部分可以用getrusage()类似的功能代替?如果具有 Unix 专业知识的人可以编辑此答案并填写详细信息?!

回答by Michael Taylor

Mac OS X

Mac OS X

I was hoping to find similar information for Mac OS X as well. Since it wasn't here, I went out and dug it up myself. Here are some of the things I found. If anyone has any other suggestions, I'd love to hear them.

我也希望为 Mac OS X 找到类似的信息。既然不在这里,我就自己出去挖了。以下是我发现的一些东西。如果有人有任何其他建议,我很乐意听取他们的意见。

Total Virtual Memory

总虚拟内存

This one is tricky on Mac OS X because it doesn't use a preset swap partition or file like Linux. Here's an entry from Apple's documentation:

这在 Mac OS X 上很棘手,因为它不像 Linux 那样使用预设的交换分区或文件。这是 Apple 文档中的一个条目:

Note:Unlike most Unix-based operating systems, Mac OS X does not use a preallocated swap partition for virtual memory. Instead, it uses all of the available space on the machine's boot partition.

注意:与大多数基于 Unix 的操作系统不同,Mac OS X 不为虚拟内存使用预先分配的交换分区。相反,它使用机器引导分区上的所有可用空间。

So, if you want to know how much virtual memory is still available, you need to get the size of the root partition. You can do that like this:

因此,如果您想知道还有多少虚拟内存可用,则需要获取根分区的大小。你可以这样做:

xsw_usage vmusage = {0};
size_t size = sizeof(vmusage);
if( sysctlbyname("vm.swapusage", &vmusage, &size, NULL, 0)!=0 )
{
   perror( "unable to get swap usage by calling sysctlbyname(\"vm.swapusage\",...)" );
}

Total Virtual Currently Used

当前使用的虚拟机总数

Calling systcl with the "vm.swapusage" key provides interesting information about swap usage:

使用“vm.swapusage”键调用 systcl 提供有关交换使用的有趣信息:

#include<mach/mach.h>

struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;

if (KERN_SUCCESS != task_info(mach_task_self(),
                              TASK_BASIC_INFO, (task_info_t)&t_info, 
                              &t_info_count))
{
    return -1;
}
// resident size is in t_info.resident_size;
// virtual size is in t_info.virtual_size;

Not that the total swap usage displayed here can change if more swap is needed as explained in the section above. So the total is actually the currentswap total. In C++, this data can be queried this way:

并不是说如果需要更多交换,则此处显示的总交换使用量会发生变化,如上一节所述。所以总数实际上是当前的掉期总数。在 C++ 中,可以这样查询这些数据:

#include <sys/types.h>
#include <sys/sysctl.h>
...
int mib[2];
int64_t physical_memory;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
length = sizeof(int64_t);
sysctl(mib, 2, &physical_memory, &length, NULL, 0);

Note that the "xsw_usage", declared in sysctl.h, seems not documented and I suspect there there is a more portable way of accessing these values.

请注意,在 sysctl.h 中声明的“xsw_usage”似乎没有记录,我怀疑有一种更便携的方式来访问这些值。

Virtual Memory Currently Used by my Process

我的进程当前使用的虚拟内存

You can get statistics about your current process using the task_infofunction. That includes the current resident size of your process and the current virtual size.

您可以使用该task_info功能获取有关当前进程的统计信息。这包括进程的当前驻留大小和当前虚拟大小。

#include <mach/vm_statistics.h>
#include <mach/mach_types.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>

int main(int argc, const char * argv[]) {
    vm_size_t page_size;
    mach_port_t mach_port;
    mach_msg_type_number_t count;
    vm_statistics64_data_t vm_stats;

    mach_port = mach_host_self();
    count = sizeof(vm_stats) / sizeof(natural_t);
    if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&
        KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,
                                        (host_info64_t)&vm_stats, &count))
    {
        long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;

        long long used_memory = ((int64_t)vm_stats.active_count +
                                 (int64_t)vm_stats.inactive_count +
                                 (int64_t)vm_stats.wire_count) *  (int64_t)page_size;
        printf("free memory: %lld\nused memory: %lld\n", free_memory, used_memory);
    }

    return 0;
}

Total RAM available

可用内存总量

The amount of physical RAM available in your system is available using the sysctlsystem function like this:

系统中可用的物理 RAM 量可使用如下sysctl系统函数获得:

Anderson cxc # more /proc/meminfo
MemTotal:      4083948 kB
MemFree:       2198520 kB
Buffers:         82080 kB
Cached:        1141460 kB
SwapCached:          0 kB
Active:        1137960 kB
Inactive:       608588 kB
HighTotal:     3276672 kB
HighFree:      1607744 kB
LowTotal:       807276 kB
LowFree:        590776 kB
SwapTotal:     2096440 kB
SwapFree:      2096440 kB
Dirty:              32 kB
Writeback:           0 kB
AnonPages:      523252 kB
Mapped:          93560 kB
Slab:            52880 kB
SReclaimable:    24652 kB
SUnreclaim:      28228 kB
PageTables:       2284 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   4138412 kB
Committed_AS:  1845072 kB
VmallocTotal:   118776 kB
VmallocUsed:      3964 kB
VmallocChunk:   112860 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

RAM Currently Used

当前使用的内存

You can get general memory statistics from the host_statisticssystem function.

您可以从host_statistics系统函数中获取一般内存统计信息。

Anderson cxc #  more /proc/stat
cpu  2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0

One thing to note here are that there are five types of memory pages in Mac OS X. They are as follows:

这里需要注意的一点是,Mac OS X 中有五种类型的内存页。它们如下:

  1. Wiredpages that are locked in place and cannot be swapped out
  2. Activepages that are loading into physical memory and would be relatively difficult to swap out
  3. Inactivepages that are loaded into memory, but haven't been used recently and may not even be needed at all. These are potential candidates for swapping. This memory would probably need to be flushed.
  4. Cachedpages that have been some how cached that are likely to be easily reused. Cached memory probably would not require flushing. It is still possible for cached pages to be reactivated
  5. Freepages that are completely free and ready to be used.
  1. 锁定到位且无法换出的有线页面
  2. 正在加载到物理内存中并且相对难以换出的活动页面
  3. 加载到内存中但最近没有使用过甚至可能根本不需要的非活动页面。这些是交换的潜在候选者。该内存可能需要刷新。
  4. 已缓存的页面可能很容易被重用。缓存内存可能不需要刷新。仍然可以重新激活缓存的页面
  5. 完全免费且随时可以使用的免费页面。

It is good to note that just because Mac OS X may show very little actual free memory at times that it may not be a good indication of how much is ready to be used on short notice.

值得注意的是,仅仅因为 Mac OS X 有时可能会显示很少的实际可用内存,因此它可能无法很好地表明有多少可以在短时间内使用。

RAM Currently Used by my Process

我的进程当前使用的 RAM

See the "Virtual Memory Currently Used by my Process" above. The same code applies.

请参阅上面的“我的进程当前使用的虚拟内存”。相同的代码适用。

回答by Martin Del Vecchio

Linux

Linux

In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.

在 Linux 中,此信息在 /proc 文件系统中可用。我不是所使用的文本文件格式的忠实粉丝,因为每个 Linux 发行版似乎都自定义了至少一个重要文件。快速浏览一下 'ps' 的来源就会发现一团糟。

But here is where to find the information you seek:

但在这里可以找到您要查找的信息:

/proc/meminfocontains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in MemTotal, MemFree, SwapTotal, and SwapFree:

/proc/meminfo包含您要查找的大部分系统范围的信息。在我的系统上看起来像这样;我认为您对MemTotalMemFreeSwapTotalSwapFree 感兴趣

cpu  2330047 0 2365006 1063853632 9035 9463 96114 0

For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.

对于 CPU 利用率,您必须做一些工作。自系统启动以来,Linux 提供整体 CPU 利用率;这可能不是你感兴趣的。如果你想知道最后一秒,或者10秒的CPU利用率是多少,那么你需要查询信息并自己计算。

The information is available in /proc/stat, which is documented pretty well at http://www.linuxhowtos.org/System/procstat.htm; here is what it looks like on my 4-core box:

该信息在/proc/stat 中可用,该信息在http://www.linuxhowtos.org/System/procstat.htm 中有很好的记录;这是我的 4 核盒子上的样子:

cpu  2330047 0 2365007 1063854028 9035 9463 96114 0

First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.

首先,您需要确定系统中有多少 CPU(或处理器,或处理核心)可用。为此,请计算“cpuN”条目的数量,其中 N 从 0 开始并递增。不要计算 'cpu' 行,它是 cpuN 行的组合。在我的示例中,您可以看到 cpu0 到 cpu3,总共有 4 个处理器。从现在开始,您可以忽略 cpu0..cpu3,而只关注 'cpu' 行。

Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux "jiffies", which are 1/100 of a second each.

接下来,您需要知道这些行中的第四个数字是空闲时间的度量,因此“cpu”行上的第四个数字是自启动以来所有处理器的总空闲时间。这个时间是在 Linux "jiffies" 中测量的,每个都是 1/100 秒。

But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:

但是你并不关心总空闲时间;您关心给定时间内的空闲时间,例如最后一秒。计算一下,您需要读取此文件两次,间隔 1 秒。然后您可以对该行的第四个值进行比较。例如,如果您抽取样本并得到:

19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0

Then one second later you get this sample:

然后一秒钟后你得到这个样本:

Name:   whatever
State:  S (sleeping)
Tgid:   19340
Pid:    19340
PPid:   19115
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak:   676252 kB
VmSize:   651352 kB
VmLck:         0 kB
VmHWM:    420300 kB
VmRSS:    420296 kB
VmData:   581028 kB
VmStk:       112 kB
VmExe:     11672 kB
VmLib:     76608 kB
VmPTE:      1244 kB
Threads:        77
SigQ:   0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed:   0f
Mems_allowed:   1
voluntary_ctxt_switches:        6518
nonvoluntary_ctxt_switches:     6598

Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.

将这两个数字相减,您会得到 396 的差异,这意味着您的 CPU 在最后 1.00 秒中空闲了 3.96 秒。当然,诀窍是您需要除以处理器数量。3.96 / 4 = 0.99,还有你的闲置百分比;99% 空闲,1% 忙碌。

In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.

在我的代码中,我有一个包含 360 个条目的环形缓冲区,我每秒都会读取这个文件。这让我可以快速计算 1 秒、10 秒等的 CPU 利用率,一直到 1 小时。

For the process-specific information, you have to look in /proc/pid; if you don't care abut your pid, you can look in /proc/self.

对于特定于进程的信息,您必须查看/proc/pid;如果你不在乎你的pid,你可以查看/proc/self。

CPU used by your process is available in /proc/self/stat. This is an odd-looking file consisting of a single line; for example:

您的进程使用的 CPU 在/proc/self/stat 中可用。这是一个看起来很奇怪的文件,只有一行;例如:

#include <windows.h>
#include <stdio.h>

    //------------------------------------------------------------------------------------------------------------------
    // Prototype(s)...
    //------------------------------------------------------------------------------------------------------------------
    CHAR cpuusage(void);

    //-----------------------------------------------------
    typedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
    static pfnGetSystemTimes s_pfnGetSystemTimes = NULL;

    static HMODULE s_hKernel = NULL;
    //-----------------------------------------------------
    void GetSystemTimesAddress()
    {
        if( s_hKernel == NULL )
        {   
            s_hKernel = LoadLibrary( L"Kernel32.dll" );
            if( s_hKernel != NULL )
            {
                s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress( s_hKernel, "GetSystemTimes" );
                if( s_pfnGetSystemTimes == NULL )
                {
                    FreeLibrary( s_hKernel ); s_hKernel = NULL;
                }
            }
        }
    }
    //----------------------------------------------------------------------------------------------------------------

    //----------------------------------------------------------------------------------------------------------------
    // cpuusage(void)
    // ==============
    // Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.
    //----------------------------------------------------------------------------------------------------------------
    CHAR cpuusage()
    {
        FILETIME               ft_sys_idle;
        FILETIME               ft_sys_kernel;
        FILETIME               ft_sys_user;

        ULARGE_INTEGER         ul_sys_idle;
        ULARGE_INTEGER         ul_sys_kernel;
        ULARGE_INTEGER         ul_sys_user;

        static ULARGE_INTEGER    ul_sys_idle_old;
        static ULARGE_INTEGER  ul_sys_kernel_old;
        static ULARGE_INTEGER  ul_sys_user_old;

        CHAR  usage = 0;

        // we cannot directly use GetSystemTimes on C language
        /* add this line :: pfnGetSystemTimes */
        s_pfnGetSystemTimes(&ft_sys_idle,    /* System idle time */
            &ft_sys_kernel,  /* system kernel time */
            &ft_sys_user);   /* System user time */

        CopyMemory(&ul_sys_idle  , &ft_sys_idle  , sizeof(FILETIME)); // Could been optimized away...
        CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...
        CopyMemory(&ul_sys_user  , &ft_sys_user  , sizeof(FILETIME)); // Could been optimized away...

        usage  =
            (
            (
            (
            (
            (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
            (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)
            )
            -
            (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)
            )
            *
            (100)
            )
            /
            (
            (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
            (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)
            )
            );

        ul_sys_idle_old.QuadPart   = ul_sys_idle.QuadPart;
        ul_sys_user_old.QuadPart   = ul_sys_user.QuadPart;
        ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;

        return usage;
    }
    //------------------------------------------------------------------------------------------------------------------
    // Entry point
    //------------------------------------------------------------------------------------------------------------------
    int main(void)
    {
        int n;
        GetSystemTimesAddress();
        for(n=0;n<20;n++)
        {
            printf("CPU Usage: %3d%%\r",cpuusage());
            Sleep(2000);
        }
        printf("\n");
        return 0;
    }

The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.

这里的重要数据是第 13 个和第 14 个令牌(这里是 0 和 770)。第13个token是进程在用户态执行的jiffies数,第14个是进程在内核态执行的jiffies数。将两者相加,就得到了它的总 CPU 利用率。

Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time.

同样,您必须定期对该文件进行采样,并计算差异,以便确定进程随时间推移的 CPU 使用率。

Edit:remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.

编辑:请记住,在计算进程的 CPU 利用率时,必须考虑 1) 进程中的线程数,以及 2) 系统中的处理器数。例如,如果您的单线程进程仅使用 25% 的 CPU,这可能是好也可能是坏。在单处理器系统上好,但在 4 处理器系统上不好;这意味着您的进程持续运行,并使用 100% 可用的 CPU 周期。

For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:

对于特定于进程的内存信息,您必须查看 /proc/self/status,如下所示:

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

The entries that start with 'Vm' are the interesting ones:

以“Vm”开头的条目是有趣的:

  • VmPeakis the maximum virtual memory space used by the process, in kB (1024 bytes).
  • VmSizeis the current virtual memory space used by the process, in kB. In my example, it's pretty large: 651,352 kB, or about 636 megabytes.
  • VmRssis the amount of memory that have been mapped into the process' address space, or its resident set size. This is substantially smaller (420,296 kB, or about 410 megabytes). The difference: my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.
  • VmPeak是进程使用的最大虚拟内存空间,单位为 kB(1024 字节)。
  • VmSize是进程当前使用的虚拟内存空间,单位为 kB。在我的示例中,它非常大:651,352 kB,或大约 636 MB。
  • VmRss是已映射到进程地址空间的内存量,或其驻留集大小。这要小得多(420,296 kB,或大约 410 MB)。不同之处:我的程序通过 mmap() 映射了 636 MB,但只访问了其中的 410 MB,因此只分配了 410 MB 的页面给它。

The only item I'm not sure about is Swapspace currently used by my process. I don't know if this is available.

我唯一不确定的项目是我的进程当前使用的 Swapspace。我不知道这是否可用。

回答by sayyed mohsen zahraee

in windows you can get cpu usage by code bellow:

在 Windows 中,您可以通过以下代码获取 CPU 使用率:

   Until Linux 2.3.16, sysinfo() used to return information in the
   following structure:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           char _f[22];             /* Pads structure to 64 bytes */
       };

   and the sizes were given in bytes.

   Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure
   is:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           unsigned long totalhigh; /* Total high memory size */
           unsigned long freehigh;  /* Available high memory size */
           unsigned int mem_unit;   /* Memory unit size in bytes */
           char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */
       };

   and the sizes are given as multiples of mem_unit bytes.

回答by Mark Lakata

Linux

Linux

A portable way of reading memory and load numbers is the sysinfocall

读取内存和加载数字的一种便携方式是sysinfo调用

Usage

用法

#include <atomic.h>
#include <libc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/iofunc.h>
#include <sys/neutrino.h>
#include <sys/resmgr.h>
#include <sys/syspage.h>
#include <unistd.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/debug.h>
#include <sys/procfs.h>
#include <sys/syspage.h>
#include <sys/neutrino.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include <devctl.h>
#include <errno.h>

#define MAX_CPUS 32

static float Loads[MAX_CPUS];
static _uint64 LastSutime[MAX_CPUS];
static _uint64 LastNsec[MAX_CPUS];
static int ProcFd = -1;
static int NumCpus = 0;


int find_ncpus(void) {
    return NumCpus;
}

int get_cpu(int cpu) {
    int ret;
    ret = (int)Loads[ cpu % MAX_CPUS ];
    ret = max(0,ret);
    ret = min(100,ret);
    return( ret );
}

static _uint64 nanoseconds( void ) {
    _uint64 sec, usec;
    struct timeval tval;
    gettimeofday( &tval, NULL );
    sec = tval.tv_sec;
    usec = tval.tv_usec;
    return( ( ( sec * 1000000 ) + usec ) * 1000 );
}

int sample_cpus( void ) {
    int i;
    debug_thread_t debug_data;
    _uint64 current_nsec, sutime_delta, time_delta;
    memset( &debug_data, 0, sizeof( debug_data ) );

    for( i=0; i<NumCpus; i++ ) {
        /* Get the sutime of the idle thread #i+1 */
        debug_data.tid = i + 1;
        devctl( ProcFd, DCMD_PROC_TIDSTATUS,
        &debug_data, sizeof( debug_data ), NULL );
        /* Get the current time */
        current_nsec = nanoseconds();
        /* Get the deltas between now and the last samples */
        sutime_delta = debug_data.sutime - LastSutime[i];
        time_delta = current_nsec - LastNsec[i];
        /* Figure out the load */
        Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );
        /* Flat out strange rounding issues. */
        if( Loads[i] < 0 ) {
            Loads[i] = 0;
        }
        /* Keep these for reference in the next cycle */
        LastNsec[i] = current_nsec;
        LastSutime[i] = debug_data.sutime;
    }
    return EOK;
}

int init_cpu( void ) {
    int i;
    debug_thread_t debug_data;
    memset( &debug_data, 0, sizeof( debug_data ) );
/* Open a connection to proc to talk over.*/
    ProcFd = open( "/proc/1/as", O_RDONLY );
    if( ProcFd == -1 ) {
        fprintf( stderr, "pload: Unable to access procnto: %s\n",strerror( errno ) );
        fflush( stderr );
        return -1;
    }
    i = fcntl(ProcFd,F_GETFD);
    if(i != -1){
        i |= FD_CLOEXEC;
        if(fcntl(ProcFd,F_SETFD,i) != -1){
            /* Grab this value */
            NumCpus = _syspage_ptr->num_cpu;
            /* Get a starting point for the comparisons */
            for( i=0; i<NumCpus; i++ ) {
                /*
                * the sutime of idle thread is how much
                * time that thread has been using, we can compare this
                * against how much time has passed to get an idea of the
                * load on the system.
                */
                debug_data.tid = i + 1;
                devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );
                LastSutime[i] = debug_data.sutime;
                LastNsec[i] = nanoseconds();
            }
            return(EOK);
        }
    }
    close(ProcFd);
    return(-1);
}

void close_cpu(void){
    if(ProcFd != -1){
        close(ProcFd);
        ProcFd = -1;
    }
}

int main(int argc, char* argv[]){
    int i,j;
    init_cpu();
    printf("System has: %d CPUs\n", NumCpus);
    for(i=0; i<20; i++) {
        sample_cpus();
        for(j=0; j<NumCpus;j++)
        printf("CPU #%d: %f\n", j, Loads[j]);
        sleep(1);
    }
    close_cpu();
}

DESCRIPTION

描述

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <err.h>
#include <sys/stat.h>
#include <sys/types.h>

int main( int argc, char *argv[] ){
    struct stat statbuf;
    paddr_t freemem;
    stat( "/proc", &statbuf );
    freemem = (paddr_t)statbuf.st_size;
    printf( "Free memory: %d bytes\n", freemem );
    printf( "Free memory: %d KB\n", freemem / 1024 );
    printf( "Free memory: %d MB\n", freemem / ( 1024 * 1024 ) );
    return 0;
} 

回答by Boernii

QNX

QNX

Since this is like a "wikipage of code" I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):

由于这就像一个“代码维基页面”,我想从 QNX 知识库中添加一些代码(注意:这不是我的工作,但我检查了它并且它在我的系统上运行良好):

How to get CPU usage in %: http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5

如何以百分比获取 CPU 使用率:http: //www.qnx.com/support/knowledgebase.html?id=50130000000P9b5

#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>

static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;

// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
// You'll need to call this at regular intervals, since it measures the load between
// the previous call and the current one.
float GetCPULoad()
{
   host_cpu_load_info_data_t cpuinfo;
   mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
   if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
   {
      unsigned long long totalTicks = 0;
      for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];
      return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);
   }
   else return -1.0f;
}

float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
  unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;
  unsigned long long idleTicksSinceLastTime  = idleTicks-_previousIdleTicks;
  float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
  _previousTotalTicks = totalTicks;
  _previousIdleTicks  = idleTicks;
  return ret;
}

How to get the free (!) memory: http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx

如何获得免费(!)内存:http: //www.qnx.com/support/knowledgebase.html?id=50130000000mlbx

   /proc/[pid]/statm
          Provides information about memory usage, measured in pages.
          The columns are:

              size       (1) total program size
                         (same as VmSize in /proc/[pid]/status)
              resident   (2) resident set size
                         (same as VmRSS in /proc/[pid]/status)
              shared     (3) number of resident shared pages (i.e., backed by a file)
                         (same as RssFile+RssShmem in /proc/[pid]/status)
              text       (4) text (code)
              lib        (5) library (unused since Linux 2.6; always 0)
              data       (6) data + stack
              dt         (7) dirty pages (unused since Linux 2.6; always 0)

回答by souch

Mac OS X - CPU

Mac OS X - CPU

Overall CPU usage:

CPU整体使用率:

From Retrieve system information on MacOS X?:

在 MacOS X 上检索系统信息?

static HANDLE self;
static int numProcessors;
SYSTEM_INFO sysInfo;

double percent;

numProcessors = sysInfo.dwNumberOfProcessors;

//Getting system times information
FILETIME SysidleTime;
FILETIME SyskernelTime; 
FILETIME SysuserTime; 
ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  

//Getting process times information
FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)

percent = 100*(numerator/denomenator);

回答by Steven Warner

For Linux You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status

对于 Linux,您还可以使用 /proc/self/statm 来获取一行包含关键进程内存信息的数字,这比从 proc/self/status 获取一长串报告信息要快

See http://man7.org/linux/man-pages/man5/proc.5.html

http://man7.org/linux/man-pages/man5/proc.5.html

##代码##

回答by Salman Ghaffar

I used this following code in my C++ project and it worked fine:

我在我的 C++ 项目中使用了以下代码,它运行良好:

##代码##