C++获取内存使用情况

在程序编程过程中,为了防止出现内存泄漏情况出现,需要持续关注内存程序内存占用情况。如下方式实现获取当前进程内存使用情况:

linux:

void my_top(string path, bool flag)
{
    if(flag)
    {
        FILE* read_top = fopen("/proc/self/status", "r");
        char line_rss[128];
        unsigned long long Pid, VmSize, VmRSS;

        while (fgets(line_rss, 128, read_top) != NULL)
        {
            if (strncmp(line_rss, "Pid:", 4) == 0)
            {
                string str(line_rss + 4);
                Pid = strtoull(str.c_str(), NULL, 19);
            }

            if (strncmp(line_rss, "VmSize:", 7) == 0)
            {
                string str(line_rss + 7);
                VmSize = strtoull(str.c_str(), NULL, 19);
            }

            if (strncmp(line_rss, "VmRSS:", 6) == 0)
            {
                string str(line_rss + 6);
                VmRSS = strtoull(str.c_str(), NULL, 19);
            }

            if(Pid < 0 || VmSize < 0 || VmRSS < 0)
            {
                fclose(read_top);
                break;
            }
        }
        fclose(read_top);

        ofstream writer_top(path, ios::app);
        writer_top << Pid << " " << VmSize << " " << VmRSS << endl;
        writer_top.close();
    }
    else
    {
        ofstream writer_top(path, ios::app);
        writer_top << "0" << " " << "0" << " " << "0" << endl;
        writer_top.close();
    }
}

其他资源:

VmPeak: 	表示进程所占用最大虚拟内存大小
VmSize:     表示进程当前虚拟内存大小
VmLck:      表示被锁定的内存大小
VmHWM:    	表示进程所占用物理内存的峰值
VmRSS:     	表示进程当前占用物理内存的大小(与procrank中的RSS)
VmData:     表示进程数据段的大小
VmStk:      表示进程堆栈段的大小
VmExe:      表示进程代码的大小
VmLib:      表示进程所使用共享库的大小
VmPTE:      表示进程页表项的大小

windows:

#include 
#include 
#include 

int main()
{
    PROCESS_MEMORY_COUNTERS pmc;
    if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
    {
        printf("当前进程占用内存大小为:%d KB\n", pmc.WorkingSetSize / 1024);
    }
    return 0;
}

另外可以通过如下方式获取文件的信息内容:

// 这是一个存储文件(夹)信息的结构体,其中有文件大小和创建时间、访问时间、修改时间等
struct stat statbuf;

// 提供文件名字符串,获得文件属性结构体
stat("path", &statbuf);

// 获取文件大小
size_t filesize = statbuf.st_size;

cout << filesize << endl;

你可能感兴趣的:(c++)