内存使用问题

时间:2011-04-22 18:52:42

标签: c++

我正在努力优化代码的内存使用情况,我发现了一个我不明白的问题。请让我知道你的想法。

代码:

typedef map <pair<string, int>, vector<pair<int, float> > > TDM;

void parsefile (TDM & my_map, string in_file); // parse input file and put it in the data map
float CheckMemUsage (void); // check memory usage by extracting /proc/self/stat info


int main (int argc, char *argv[]) {
  TDM my_map;
  string infile = "xxx";

  printf ("INFO: Memory usage before parse file: %.2fM.\n", CheckMemUsage ());
  parsefile (my_map, in_file);
  printf ("INFO: Memory usage after parse file: %.2fM.\n", CheckMemUsage ());

  for (TDM::iterator it=my_map.begin(); it!=my_map.end(); ++it) {
    vector<pair<int, float> > ().swap (it->second);
  }
  TDM ().swap (my_map);
  printf ("INFO: Memory usage after delete map: %.2fM.\n", CheckMemUsage ());
}

该计划的报告:

INFO: Memory usage before parse file: 13.46M.
INFO: Memory usage after parse file: 203.53M.
INFO: Memory usage after delete map: 132.59M.

在函数“parsefile”中,我只使用字符串,向量,对,映射填充,而没有新的任何内存。所以在这个程序之后,我假设只有my_map在内存中。删除我的地图后,内存使用量应在解析文件状态(13.46M)之前返回。但它仍然报告了132.59M。这个132M是什么用的?我的程序中有错误吗?

非常感谢你的时间。

2 个答案:

答案 0 :(得分:2)

仅仅因为你从堆中释放了内存,这是std::map在后​​台使用它来实现其存储的内存,并不意味着在程序执行期间内存会返回给操作系统。

答案 1 :(得分:1)

我同意Andy,虽然我会说数据结构在销毁时会将内存返回到

除非您的分配器正在使用mmap或类似的技巧,否则您可能正在使用DLMalloc的某些变体(即使在某些情况下可以使用mmap,但我知道它并不常见)。请阅读Doug Lea's paper以获得一些见解。