首先,我在做std::ios_base::sync_with_stdio(false)
。我有以下的代碼段,從文本文件(<input.txt >output.txt
)讀一百萬個整數:交替cin/cout慢?
int tests;
cin >> tests;
for (int i = 0; i < tests; ++i) {
int number;
cin >> number;
cout << number << "\n";
}
和
int tests;
cin >> tests;
vector<int> numbers(tests);
for (int i = 0; i < tests; ++i) {
cin >> numbers[i];
}
for (int i = 0; i < tests; ++i) {
cout << numbers[i] << "\n";
}
當然,在現實中,他們要做的不僅僅是打印相同的數字更多。問題是,第一塊需要大約4倍(6.2秒比1.8)。
在兩種情況下重寫相同的代碼與printf
/scanf
需要3秒鐘。這背後的原因是什麼?
'cin'領帶和'cout'是['領帶()'d](http://en.cppreference.com/w/cpp/io/basic_ios/ tie)在另一個上調用'flush()'操作。 – 2014-12-02 15:53:34
是不是'sync_with_stdio'應該防止什麼? – riv 2014-12-02 15:55:16
不,這說明了'cout'和'printf'之間的聯繫。不在'cout'和'cin'之間。 – 2014-12-02 15:56:22