gpt4 book ai didi

c++ - C++ 中字符串流与文件 I/O 流的性能对比

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:24:01 26 4
gpt4 key购买 nike

我必须读入一个巨大的文本文件(>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
}

关于c++ - C++ 中字符串流与文件 I/O 流的性能对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4099596/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com