簡體   English   中英

為什么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來工作。 由於緩沖區的大小,這可能意味着需要進行更多的OS調用,但是更重要的是,這還意味着需要反復設置和拆除iostream哨兵,這可能意味着互斥鎖,並且通常還意味着很多其他東西。 此外, operator>>是格式化的操作,而read是未格式化的,這是每個操作的額外設置開銷。

編輯:疲倦的眼睛看到了istream_iterator而不是istreambuf_iterator。 當然,istreambuf_iterator不執行格式化輸入。 它在流緩沖上調用sbumpc或類似的名稱。 仍然有很多調用,並使用了緩沖區,該緩沖區可能比整個文件小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM