endl和'\ n'之间的区别

时间:2012-11-24 21:42:07

标签: c++ stream outputstream

  

可能重复:
  C++: “std::endl” vs “\n”

我有一个我测试的简单程序,我意识到endl对我的程序造成了严重破坏。使用endl,我的程序在使用'\n'时运行 100+ ms ,时间降至 ~50ms 。 有谁能说出为什么会有这样的差异?

P.S。我确实阅读了其他帖子,以某种方式解释了他们每个人在做什么,但std::flush真的花了这么多时间吗? 或者还有其他可能的解释吗?

2 个答案:

答案 0 :(得分:6)

std::endl会写一个换行符并刷新缓冲区。正如您所发现的那样,冲洗可能是一项相当昂贵的操作。

答案 1 :(得分:2)

endl有额外费用flush()操作

27.7.3.8标准basic_ostream操纵器[ostream.manip]

namespace std {
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}
1 Effects: Calls os.put(os.widen(’\n’)), then os.flush().
2 Returns: os.