在C ++程序使用scanf()的是比使用CIN快? [英] Using scanf() in C++ programs is faster than using cin?
问题描述
我不知道这是不是真的,但是,当我开始提供网站问题的一个常见问题阅读,我找到了,那捅了我的注意:
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.
有人能澄清这?真的是使用的 scanf()的的在C ++程序的速度比使用的 CIN >>东西的?如果是的话,那就是它一个很好的做法在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++...
推荐答案
下面是一个简单的情况下快速测试:一个程序来读取从标准输入和XOR所有号码的号码列表
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\n", parity);
return 0;
}
结果
使用的第三方案,我生成包含33280276随机数的文本文件。的执行时间是:
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.
这样:真的有速度差
的编辑:的用户clyfish 下面指出的是速度差主要是由于iostream的I / O功能,保持与CI / O功能的同步。我们可以通过调用关闭此功能,以的std :: IOS :: sync_with_stdio(假);
:
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。如果我们不混合cstdio和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 cstdio and iostream, we can turn it off, and then iostream is fastest.
在code: https://gist.github.com/3845568
这篇关于在C ++程序使用scanf()的是比使用CIN快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!