c++ - 为什么从 mmaped 文件构建 std::string 这么慢?

标签 c++ multithreading c++11

我正在尝试处理大文件,现在我有文件 加载到内存和以下解析函数:

在第一种情况下,我从文件的一部分构造字符串(读取 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/

相关文章:

c++ - 如何使用基于范围的循环语法遍历 STL 容器中的连续对?

c++ - 将值输出到不同大小的缓冲区

c++ - 如何确保函数在 C/C++ 中返回一致的浮点值?

c++ - SQL Null返回 "stops"使用odbc在c++中返回

java - 在短时间内用 Java 执行数百万个任务?

c++ - constexpr 替换数学常量,如 M_PI

c++ - 构造函数中的虚函数调用

ios - Swift ios alamofire put请求错误Thread 1 : signal SIGABRT at

c++ - thread::get_id (C++11) 是免费的吗?

c++ - 检测 C++ lambda 是否可以转换为函数指针