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().

每次写入一个换行符的时候都会将缓冲区的内容写入到输出的对象中,速度会受到很大影响。

性能测试

#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倍。