我必须阅读一个巨大的文本文件(> 200,000 个单词)并处理每个单词。我将整个文件读入一个字符串,然后将一个字符串流附加到它以轻松处理每个单词。方法是我直接从文件中输入每个单词并使用<<
它进行处理,但是比较这两种方法在执行时间方面没有给我任何优势。对内存中的字符串进行操作是否比在每次需要一个单词时都需要系统调用的文件中操作更快?请建议一些性能增强方法。
对于性能和最少的复制,这是很难被击败的(只要你有足够的内存!):
void mapped(const char* fname)
{
using namespace boost::interprocess;
//Create a file mapping
file_mapping m_file(fname, read_only);
//Map the whole file with read permissions
mapped_region region(m_file, read_only);
//Get the address of the mapped region
void * addr = region.get_address();
std::size_t size = region.get_size();
// Now you have the underlying data...
char *data = static_cast<char*>(addr);
std::stringstream localStream;
localStream.rdbuf()->pubsetbuf(data, size);
// now you can do your stuff with the stream
// alternatively
}
Run Code Online (Sandbox Code Playgroud)