跟踪c ++中的相对内存使用情况17

时间:2018-01-23 06:40:42

标签: c++ memory c++17

我试图理解C ++中内存管理的复杂性,以便向我的学生传授它。由于最好的学习方法是尝试,我想尝试几个代码片段,看看它们如何影响内存使用情况。例如,我想尝试以下内容以了解唯一指针的工作原理:

#include <memory>
using namespace std;

int main() 
{
    {
        // print memory - should be X
        auto i = make_unique<int>();
        // print memory - should be X-4
    }
    // print memory - should be X
}

我写的评论是基于我目前的理解,这当然可能是错的;我想检查一下我是否理解正确。我的问题是:我可以写什么而不是“打印记忆”?

我发现了几个明显相似的问题,例如:How to determine CPU and memory consumption from inside a process?C++: Measuring memory usage from within the program, Windows and Linux。但是,那里的答案非常复杂且与平台有关。我的需求要简单得多:我不需要程序的绝对内存消耗(即,我不需要X准确)。我需要的是一个相对测量,它将向我展示我的行为如何影响内存消耗。 对于这种需求,是否有更简单的解决方案?

2 个答案:

答案 0 :(得分:3)

难道你不能让unique_ptr保持一个大于整数的结构,保持Kbs而不是字节吗?然后可能只是检查任务管理器中的进程内存(或者您的操作系统使用的任何内容),您可以向学生逐步查看代码。

答案 1 :(得分:1)

根据Jorge Y.的回答,我创建了以下程序。它不是最佳的,因为(a)它只适用于Linux,(b)它要求我在程序控制台之外保持一个终端窗口打开以跟踪内存。但是,至少它有利于演示目的。

#include <iostream>
#include <memory>
#include <vector>
#include <thread>
#include <chrono>
using namespace std;

#define USE_UNIQUE_PTR

constexpr int SIZE=1000*1000*1000;
struct Large {
    char x[SIZE];
};

int main() {
    cout << "Before braces" << endl;
    this_thread::sleep_for(chrono::milliseconds(5000));
    // On Linux, run:    cat /proc/meminfo |grep MemFree
    // Available memory is X
    {
        #ifdef USE_UNIQUE_PTR
        auto p = make_unique<Large>();
        #else
        auto p = new Large();
        #endif
        cout << "Inside braces" << endl;
        p->x[0] = 5;
        cout << p->x[0] << endl;
        this_thread::sleep_for(chrono::milliseconds(5000));
        // On Linux, run:    cat /proc/meminfo |grep MemFree
        // Available memory should be X-SIZE
    }
    cout << "Outside braces" << endl;
    this_thread::sleep_for(chrono::milliseconds(5000));
    // On Linux, run:    cat /proc/meminfo |grep MemFree
    // Available memory should be X if USE_UNIQUE_PTR is defined, X-SIZE if it is undefined.
}
相关问题