How to get current CPU and RAM usage in C++?

后端 未结 9 966
后悔当初
后悔当初 2020-12-01 06:44

is it possible, in C++, to get the current RAM and CPU usage? Is there a platform-indepentent function call?

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 07:00

    On Linux, this will use /proc/self/status . More work is required to turn this into a number. I find this useful as it is though, just to print the memory usage directly to the screen as a string.

    static string memory_usage() {
            ostringstream mem;
            PP("hi");
            ifstream proc("/proc/self/status");
            string s;
            while(getline(proc, s), !proc.fail()) {
                    if(s.substr(0, 6) == "VmSize") {
                            mem << s;
                            return mem.str();
                    }
            }
            return mem.str();
    }
    

提交回复
热议问题