テキストを標準出力に出力するさまざまな方法の違いを計っています。をテストしてcoutおりprintf、 とostringstreamの両方\nを使用していstd::endlます。私std::endlは違いを生むことを期待していましたがcout(実際にそうでした)、出力が遅くなるとは思っていませんでしたostringstream。std::endlusingはストリームに a を書き込むだけで、\n一度だけフラッシュされると思いました。何が起きてる?ここにすべての私のコードがあります:
// cout.cpp
#include <iostream>
using namespace std;
int main() {
  for (int i = 0; i < 10000000; i++) {
    cout << "Hello World!\n";
  }
  return 0;
}
// printf.cpp
#include <stdio.h>
int main() {
  for (int i = 0; i < 10000000; i++) {
    printf("Hello World!\n");
  }
  return 0;
}
// stream.cpp
#include <iostream>
#include <sstream>
using namespace std;
int main () {
  ostringstream ss;
  for (int i = 0; i < 10000000; i++) {
    ss << "stream" << endl;
  }
  cout << ss.str();
}
// streamn.cpp
#include <iostream>
#include <sstream>
using namespace std;
int main () {
  ostringstream ss;
  for (int i = 0; i < 10000000; i++) {
    ss << "stream\n";
  }
  cout << ss.str();
}
そして、これが私のMakefileです
SHELL:=/bin/bash
all: cout.cpp printf.cpp
    g++ cout.cpp -o cout.out
    g++ printf.cpp -o printf.out
    g++ stream.cpp -o stream.out
    g++ streamn.cpp -o streamn.out
time:
    time ./cout.out > output.txt
    time ./printf.out > output.txt
    time ./stream.out > output.txt
    time ./streamn.out > output.txt
makeこれが私が実行したときに得られるものですmake time
time ./cout.out > output.txt
real    0m1.771s
user    0m0.616s
sys 0m0.148s
time ./printf.out > output.txt
real    0m2.411s
user    0m0.392s
sys 0m0.172s
time ./stream.out > output.txt
real    0m2.048s
user    0m0.632s
sys 0m0.220s
time ./streamn.out > output.txt
real    0m1.742s
user    0m0.404s
sys 0m0.200s
これらの結果は一貫しています。