問題描述
我不知道這是否屬實,但是當我閱讀有關提供問題的網站之一的常見問題解答時,我發現了一些引起我注意的東西:
I don't know if this is true, but when I was reading FAQ on one of the problem providing sites, I found something, that poke my attention:
檢查您的輸入/輸出方法.在 C++ 中,使用 cin 和 cout 太慢了.使用這些,您將保證無法通過大量輸入或輸出解決任何問題.改用 printf 和 scanf.
Check your input/output methods. In C++, using cin and cout is too slow. Use these, and you will guarantee not being able to solve any problem with a decent amount of input or output. Use printf and scanf instead.
有人可以澄清一下嗎?在 C++ 程序中使用 scanf() 真的比使用 cin >> something 更快嗎?如果是,在 C++ 程序中使用它是一個好習慣嗎?我認為它是特定于 C 的,雖然我只是在學習 C++...
Can someone please clarify this? Is really using scanf() in C++ programs faster than using cin >> something ? If yes, that is it a good practice to use it in C++ programs? I thought that it was C specific, though I am just learning C++...
推薦答案
這是一個簡單案例的快速測試:一個從標準輸入讀取數字列表并對所有數字進行異或的程序.
Here's a quick test of a simple case: a program to read a list of numbers from standard input and XOR all of the numbers.
iostream 版本:
#include <iostream>
int main(int argc, char **argv) {
int parity = 0;
int x;
while (std::cin >> x)
parity ^= x;
std::cout << parity << std::endl;
return 0;
}
scanf 版本:
#include <stdio.h>
int main(int argc, char **argv) {
int parity = 0;
int x;
while (1 == scanf("%d", &x))
parity ^= x;
printf("%d
", parity);
return 0;
}
結果
使用第三個程序,我生成了一個包含 33,280,276 個隨機數的文本文件.執行時間為:
Using a third program, I generated a text file containing 33,280,276 random numbers. The execution times are:
iostream version: 24.3 seconds
scanf version: 6.4 seconds
改變編譯器的優化設置似乎根本沒有改變結果.
Changing the compiler's optimization settings didn't seem to change the results much at all.
因此:確實存在速度差異.
Thus: there really is a speed difference.
用戶 clyfish 在下面指出速度差異主要是由于iostream I/O 函數與 CI/O 函數保持同步.我們可以通過調用 std::ios::sync_with_stdio(false);
:
User clyfish points out below that the speed difference is largely due to the iostream I/O functions maintaining synchronization with the C I/O functions. We can turn this off with a call to std::ios::sync_with_stdio(false);
:
#include <iostream>
int main(int argc, char **argv) {
int parity = 0;
int x;
std::ios::sync_with_stdio(false);
while (std::cin >> x)
parity ^= x;
std::cout << parity << std::endl;
return 0;
}
新結果:
iostream version: 21.9 seconds
scanf version: 6.8 seconds
iostream with sync_with_stdio(false): 5.5 seconds
C++ iostream 勝出! 事實證明,這種內部同步/刷新通常會減慢 iostream i/o.如果我們不混合使用 stdio 和 iostream,我們可以將其關閉,然后 iostream 是最快的.
C++ iostream wins! It turns out that this internal syncing / flushing is what normally slows down iostream i/o. If we're not mixing stdio and iostream, we can turn it off, and then iostream is fastest.
代碼:https://gist.github.com/3845568
這篇關于在 C++ 程序中使用 scanf() 比使用 cin 快嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!