奇怪的内存使用量输出

时间:2013-03-15 05:37:56

标签: c++

我在How to get memory usage at run time in c++?中遇到了一段代码。代码是由于@DonWakefield我运行了两个代码实例并获得了不同的结果。

Code:
#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>

//////////////////////////////////////////////////////////////////////////////
//
// process_mem_usage(double &, double &) - takes two doubles by reference,
// attempts to read the system-dependent data for a process' virtual memory
// size and resident set size, and return the results in KB.
//
// On failure, returns 0.0, 0.0

void process_mem_usage(double& vm_usage, double& resident_set)
{
using std::ios_base;
using std::ifstream;
using std::string;

vm_usage     = 0.0;
resident_set = 0.0;

// 'file' stat seems to give the most reliable results
//
ifstream stat_stream("/proc/self/stat",ios_base::in);

// dummy vars for leading entries in stat that we don't care about
//
string pid, comm, state, ppid, pgrp, session, tty_nr;
string tpgid, flags, minflt, cminflt, majflt, cmajflt;
string utime, stime, cutime, cstime, priority, nice;
string O, itrealvalue, starttime;

// the two fields we want
//
unsigned long vsize;
long rss;

stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
           >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
           >> utime >> stime >> cutime >> cstime >> priority >> nice
           >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the 
rest

stat_stream.close();

long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to  
use 2MB pages
vm_usage     = vsize / 1024.0;
resident_set = rss * page_size_kb;
}

Test1#
int main()
{
 using std::cout;
 using std::endl;

 std::vector<int> vec1;
 double vm, rss;
 double vm1, rss1;

 process_mem_usage(vm, rss);

 vec1.resize(800000);

 process_mem_usage(vm1, rss1);
 cout << "VM: " << vm1-vm << "; RSS: " << rss1-rss << endl;

 vec1.erase(vec1.begin(), vec1.end());
 process_mem_usage(vm1, rss1);
 cout << "VM: " << vm1-vm << "; RSS: " << rss1-rss << endl;
 }

 Output:
 VM: 3128; RSS: 3208
 VM: 3132; RSS: 3316

 Test2#
 int main() 
 {
 using std::cout;
 using std::endl;
 int *vec1;
 double vm, rss;
 double vm1, rss1;

 process_mem_usage(vm, rss);

 vec1 = new int [800000];

 process_mem_usage(vm1, rss1);
 cout << "VM: " << vm1-vm << "; RSS: " << rss1-rss << endl;

 delete[] vec1;
 process_mem_usage(vm1, rss1);
 cout << "VM: " << vm1-vm << "; RSS: " << rss1-rss << endl;
 }

 Output:
 VM: 3128; RSS: 76
 VM: 4; RSS: 180

为什么这些测试表现不同。结果不应该更接近彼此吗?即使向量/指针消耗的内存也不会反映在输出中。

我的另一个问题是输出显示向量占用大内存,而test2#显示占用低内存的int数组。 80k整数将需要3125kB的内存。为什么会有区别?

1 个答案:

答案 0 :(得分:0)

vector的基础结构是一个数组,可能大于或等于已填充元素的数量(这称为capacity的{​​{1}})。这是为了防止在插入和删除元素时不断重新分配整个数组。

当你vector元素时,容量不会改变,底层结构仍然存在。

This question介绍了如何更改容量。推荐的方式似乎是:

erase