【问题标题】:Tracking relative memory usage in c++17在 c++17 中跟踪相对内存使用情况
【发布时间】:2018-07-01 21:55:11
【问题描述】:

我试图了解 C++ 中内存管理的复杂性,以便将它教给我的学生。由于最好的学习方法是通过尝试,我想尝试几个代码 sn-ps,看看它们如何影响内存使用。例如,为了了解唯一指针的工作原理,我想尝试以下操作:

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

我写的cmets是基于我目前的理解,当然可能是错误的;我想检查我是否理解正确。我的问题是:我可以写什么来代替“打印记忆”?

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

【问题讨论】:

  • 你可以自己写分配器/重载new
  • @appleapple 这不会处理堆栈上分配的内存。
  • ...我想您可以将“复杂”方法包装到方法/库中。
  • @user202729 是对的,但根据 OP 写的内容,我认为他对动态内存更感兴趣。顺便说一句,对于堆栈内存,通常对象的地址就足够了。
  • 为什么不直接在内存分析器下运行呢?

标签: c++ memory c++17


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    按照 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.
    }
    

    【讨论】:

    • 我很高兴该解决方法对您有用。在 Windows 中,您可以将任务管理器用于相同目的。在任务管理器中,您有“进程”选项卡,其中可用列之一是进程使用的内存。这应该显示程序中发生的内存变化。
    猜你喜欢
    • 2011-02-19
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2012-11-09
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多