我测试了两种写入配置:
-
Fstream缓冲:
// Initialization
const unsigned int length = 8192;
char buffer[length];
std::ofstream stream;
stream.rdbuf()->pubsetbuf(buffer, length);
stream.open("test.dat", std::ios::binary | std::ios::trunc)
// To write I use :
stream.write(reinterpret_cast<char*>(&x), sizeof(x));
-
手动缓冲:
// Initialization
const unsigned int length = 8192;
char buffer[length];
std::ofstream stream("test.dat", std::ios::binary | std::ios::trunc);
// Then I put manually the data in the buffer
// To write I use :
stream.write(buffer, length);
我期待同样的结果...
但是我的手动缓冲在写入 100MB 的文件时将性能提高了 10 倍,并且 fstream 缓冲与正常情况相比没有任何改变(无需重新定义缓冲区)。
有人对这种情况有解释吗?
EDIT :
Here are the news : a benchmark just done on a supercomputer (linux 64-bit architecture, lasts intel Xeon 8-core, Lustre filesystem and ... hopefully well configured compilers)
(and I don't explain the reason of the "resonance" for a 1kB manual buffer...)
EDIT 2 :
And the resonance at 1024 B (if someone has an idea about that, I'm interested) :
这主要是由于函数调用开销和间接性造成的。 ofstream::write() 方法继承自ostream。该函数未内联到 libstdc++ 中,这是开销的第一个来源。然后ostream::write()必须调用rdbuf()->sputn()来进行实际的写入,这是一个虚函数调用。
最重要的是,libstdc++ 将 sputn() 重定向到另一个虚拟函数 xsputn(),这添加了另一个虚拟函数调用。
如果您自己将字符放入缓冲区,则可以避免这种开销。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)