std::endl为什么导致程序变慢

最近在写hadoop的streaming任务,在输出的时候用了std::endl,就像下面这样:

os << "content" << std::endl

运行后发现程序跑的比python还慢,令人费解。我入门C++的时候,输出hello world也是这样写的,有什么问题?

于是查了一下std::endl,发现问题挺大。std::endl解释如下:

Inserts a new-line character and flushes the stream.
Its behavior is equivalent to calling os.put('\n') (or os.put(os.widen('\n')) for character types other than char), and then os.flush().

也就是说每次执行到std::endl的时候都会将缓冲区的内容写入到输出的对象中,这样一来速度慢也就不足为奇。

性能测试

#include "timer.h"
#include <fstream>
#include <iostream>

int main() {
    {
        Timer timer;
        fstream fs("./with_endl.txt", std::fstream::out);
        for (int i = 0; i<100000; i++) {
            fs << "test" << std::endl;
        }
        std::cout << "with endl:" << timer.elapsed() << "ms \n";
    }

    {
        Timer timer;
        fstream fs("./without_endl.txt", std::fstream::out);
        for (int i = 0; i<100000; i++) {
            fs << "test" << "\n";
        }
        std::cout << "without endl:" <<timer.elapsed() << "ms \n";
    }

}
with endl:397ms 
without endl:18ms 

不加std::endl性能高出20倍。如果程序的逻辑十分简单,那么输出字符串的时候最好用"\n"代替加std::endl

你可能还喜欢下面这些文章

如何避免GIT修改文件权限导致的提交变更

默认情况下当文件权限变更的时候,GIT会认为该文件有变更,提交的时候会将权限变更的文件一并提交上去,这样会让我们的代码修改记录变得混乱。解决方案解决方案很简单,忽略文件权限的变更。使用如下命令: