C++のiostreamは遅いという話

大量の入出力データを扱う課題を解く際に,入出力の処理に cin, cout ストリームを使用した C++ プログ
ラムは scanf, printf 関数を使用した同等のプログラムに比べてとても遅くなることに注意してほしい.よっ
て,cin / cout ストリームを使用しているのであれば,代わりに scanf / printf を使用することを強く薦める.
しかし,それでも cin / cout を使いたい場合は,プログラムの冒頭に次の行

ios::sync_with_stdio(false);

を加え,その上で endl を決して使用せずに代わりに “\n” を使用することを薦める.
ただし,ios::sync_with_stdio(false); を含むと cin / cout と scanf / printf を同時に使えなくなること
に注意せよ.つまり,上の行を使用する場合は,cin と scanf を混在させたり,cout と printf を混在させた
りしてはならない.

(IOI2009(Bulgaria) Technical Information(Japanese translation)より)

というわけで、軽くベンチマーク

#include <cstdio>
#include <iostream>
using namespace std;
#define COUNT 10000000
#define A 1

int main(int argc, char **argv) {
    if(argc < 2) {
        fprintf(stderr, "./test [1|2|3]\n");
        return 1;
    }
    int test_type;
    if(sscanf(argv[1], "%d", &test_type)<1 || test_type<1 || 3<test_type) {
        fprintf(stderr, "./test [1|2|3]\n");
        return 1;
    }
    if(test_type == 1) {
        for(int i = 0; i < COUNT; i++) {
            int x;
            scanf("%d", &x);
            printf("%d\n", x+1);
        }
    } else if(test_type == 2) {
        ios::sync_with_stdio(false);
        for(int i = 0; i < COUNT; i++) {
            int x;
            cin >> x;
            cout << (x+1) << "\n";
        }
    } else {
        for(int i = 0; i < COUNT; i++) {
            int x;
            cin >> x;
            cout << (x+1) << endl;
        }
    }
    return 0;
}
% time (yes 10 | ./test 1 > /dev/null)
(; yes 10 | ./test 1 > /dev/null; )  4.28s user 0.03s system 79% cpu 5.431 total
% time (yes 10 | ./test 2 > /dev/null)
(; yes 10 | ./test 2 > /dev/null; )  7.74s user 2.55s system 88% cpu 11.689 total
% time (yes 10 | ./test 3 > /dev/null)
(; yes 10 | ./test 3 > /dev/null; )  12.89s user 2.71s system 88% cpu 17.653 total

というわけで、軽くベンチマークした感じでは

  • scanf/printf…1倍
  • cin/cout(同期削減)…2倍
  • cin/cout(ふつう)…3倍

という感じだと思われる。