为什么 ifstream::read 比使用迭代器快得多
Why is ifstream::read much faster than using iterators?
实际上,有许多方法可以将文件读入字符串。两个常见的是使用 ifstream::read 直接读取字符串和使用 steambuf_iterators 和 std::copy_n:
使用 ifstream::read:
std::ifstream in {"./filename.txt"};
std::string contents;
in.seekg(0, in.end);
contents.resize(in.tellg());
in.seekg(0, in.beg);
in.read(&contents[0], contents.size());
使用 std::copy_n:
std::ifstream in {"./filename.txt"};
std::string contents;
in.seekg(0, in.end);
contents.resize(in.tellg());
in.seekg(0, in.beg);
std::copy_n(std::streambuf_iterator<char>(in),
contents.size(),
contents.begin();
许多基准测试表明,第一种方法比第二种方法快得多(在我的机器中使用 g++-4.9 时,使用 -O2 和 -O3 标志的速度大约快 10 倍),我想知道这种性能差异的原因可能是什么。
read
是单个 iostream 设置(每个 iostream 操作的一部分)和对操作系统的单个调用,直接读取您提供的缓冲区。
迭代器的工作原理是使用 operator>>
重复提取单个char
。由于缓冲区大小,这可能意味着更多的操作系统调用,但更重要的是,它还意味着重复设置和拆除iostream哨兵,这可能意味着互斥锁,通常意味着一堆其他东西。此外,operator>>
是格式化操作,而read
是未格式化的操作,这是每个操作的额外设置开销。
编辑:疲惫的眼睛看到istream_iterator而不是istreambuf_iterator。当然,istreambuf_iterator不做格式化输入。它在streambuf上称为sbumpc或类似的东西。仍然有很多调用,并使用缓冲区,它可能小于整个文件。
相关文章:
- 多流迭代器 c++
- 将多个 for 循环组合成单个迭代器
- 插入 boost::multi_index 后迭代器变得无效?
- 具有C++迭代器参数的多功能函数
- 在C++中,是否可以在单个循环中顺序迭代多个迭代器
- 如何使equal_range迭代器在 Boost 多索引中按不同的索引排序?
- 在多个 STL 对对象上创建迭代器
- 静态包装库的多态迭代器,而不向用户公开库
- 为什么迭代 std::array 比迭代 std::vector 快得多?
- C 迭代器比索引慢得多
- 前向迭代器与多个绑定相结合的迭代速度太快
- 使用迭代器从Boost多指数中删除项目时的一致性
- 为什么 ifstream::read 比使用迭代器快得多
- 集合迭代器处的多个标记
- C++映射/设置迭代器在使用多映射时出现不可增加的错误
- 为什么STL算法使用指针比std::向量迭代器快得多
- 将迭代器返回到多映射中最接近指定时间的时间
- 在相同的.obj模型文件上,Assimp查看器比Assimp c++导入器快得多
- 编写一个迭代器,使多个容器看起来像一个容器
- Visual C++,使用相同迭代器名称的多个for循环,在调试模式下在范围外可见