0

假设我有一个长度为 100MB 的缓冲区char[100*1024*1024]。我想在这个缓冲区上使用 stringstream 工具,比如格式读取,所以我stringstream ss(arr)使用这个数组定义了一个新的。所以我想知道我的程序在运行时是否总共使用了 200MB?我正在研究大数据,内存使用至关重要。实际上我定义了一个字符缓冲区并用这个缓冲区初始化我的自定义 istream 并解决了我的内存问题。但是我仍然对我的第二种方式是否多余感到困惑。

4

1 回答 1

1

所以我想知道我的程序在运行时是否总共使用了 200MB?

如果stringstream从 char 数组构造 a ,它至少会使内存使用量增加一倍。从std::basic_stringstream构造函数的参考:

使用 str 的副本作为底层字符串设备的初始内容。

您可以编写自己的流缓冲区来创建非拥有的字符串流,但boost::iostreams库已经通过数组设备提供了它。

namespace io = boost::iostreams;

char str[100*1024*1024];

// No copy of str is made here! The stream just stores pointer and size of array.
io::stream<io::array_source> strm( str, sizeof(str) );

// Do something with the stream as usual. It is fully compatible with standard streams.
int x;
strm >> x;

有一个很好的在线编译器可以显示内存使用的峰值。在以下示例中,我从 10 MiB 数组创建流。

使用std::stringstream. 峰值为 31(!) MiB。

使用boost::array_source. 峰值仅为 11 MiB。

为什么在使用char 数组大小时内存使用峰值甚至是 char 数组大小的3 倍std::stringstreamstring因为我们必须首先从 char 数组中创建一个临时对象,因为std::stringstream没有使用 char 指针的构造函数。

于 2017-03-31T20:02:11.553 回答