简体   繁体   English

std :: istream ::获取效率

[英]std::istream::get efficiency

c++ question. C ++问题。

for(i=1;i<10000;i++){
    cout << myfile.get();
}

Will program make 10000 IO operations on the file in HDD? 程序将对HDD中的文件进行10000 IO操作吗? (given that file is larger) If so, maybe it is better to read lets say 512 bytes to some buffer and then take char by char from there and then again copy 512 bytes and so on? (如果文件更大),如果这样,也许最好先说说512字节到某个缓冲区,然后从那里逐个字符地读取char,然后再复制512字节,依此类推?

As others have said - try it. 正如其他人所说的-试试吧。 Tests I've done show that reading a large block in one go (using streams) can be up to twice as fast as depending solely on the stream's own buffering. 我所做的测试表明,一次读取一个大块(使用流)的速度可以高达仅依赖于流自身的缓冲的两倍。 However, this is dependent on things like buffer size and (I would expect) stream library implementation - I use g++. 但是,这取决于诸如缓冲区大小和(我希望)流库实现的事情-我使用g ++。

您的操作系统将缓存该文件,因此您无需优化此文件即可正常使用。

ifstream已缓冲,因此,否。

Try it. 试试吧。

However, in many cases, the fastest operation will be to read the whole file at once, and then work on in-memory data. 但是,在许多情况下,最快的操作是一次读取整个文件,然后处理内存中的数据。

But really, try out each strategy, and see what works best. 但实际上,请尝试每种策略,然后看看哪种方法最有效。

Keep in mind though, that regardless of the underlying file buffering mechanism, reading one byte at a time is slow . 但是请记住,不管底层的文件缓冲机制如何,一次读取一个字节都是很慢的 If nothing else, it calls the fairly slow IOStreams library 10000 times, when you could have done just a couple of calls. 如果没有别的,它可以调用相当慢的IOStreams库10000次,而您只需要执行几次调用即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM