我正在尝试处理大文件,现在我有文件 加载到内存和以下解析函数:
在第一种情况下,我从文件的一部分构造字符串(读取 csv 的标题),第一个函数:
void csv_parse_items_file(const char* file, size_t fsize,
//void(*deal)(const string&, const size_t&, const int&),
size_t arrstart_counter = 0) {
size_t idx = 0;
int line = 0;
size_t last_idx = 0;
int counter = 0;
cout<<"items_header before loop, thread_id="+std::to_string(thread_index())<<endl;
map<string, int> headers;
{
int counter = 0;
while (file[idx] && file[idx] != '\n') {
if (file[idx] == '\t' || file[idx] == '\n') {
string key(file, last_idx, idx - last_idx);
headers[key] = counter++;
last_idx = idx + 1;
}
++idx;
}
}
cout<<"items_header after loop, thread_id="+std::to_string(thread_index())<<endl;
... then the processing continues in a loop
与文件大小(86431022 和 237179072)相比,头文件少于 1000 个字符。
但仍然执行此行 string key(file, last_idx, idx - last_idx);
需要很长时间;
$g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/binrocessing_items:1306054
使用 g++ -pthread -c -g -std=c++11
编译
用 mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
映射的文件
最佳答案
string key(file, last_idx, idx - last_idx);
等同于 string key(std::string(file), last_idx, idx - last_idx);
.每次循环都复制整个文件,然后提取其中的一小部分。
让它成为string key(file + last_idx, idx - last_idx);
关于c++ - 为什么从 mmaped 文件构建 std::string 这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706293/