【c++输入速度比较】
这个cin和scanf有什么不同啊???
首先我们生成100w个数字
1 2 3 4 5 6 7 8 9 10 11 |
#include <cstdio> #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main(){ freopen("data.in","w",stdout); for(int i=1;i<=1000000;i++) cout<<rand()<<' '; return 0; } |
然后尝试来个数组用cin读入试试时间要多少
1 2 3 4 5 6 7 8 9 10 |
#include <cstdio> #include <iostream> using namespace std; int a[1000001]; int main(){ freopen("data.in","r",stdin); for(int i=1;i<=1000000;i++) cin>>a[i]; return 0; } |
大致耗时如下
我的电脑实测稳定在600ms左右
然后我们尝试一下用scanf读入试试
1 2 3 4 5 6 7 8 9 10 |
#include <cstdio> #include <iostream> using namespace std; int a[1000001]; int main(){ freopen("data.in","r",stdin); for(int i=1;i<=1000000;i++) scanf("%d",&a[i]); return 0; } |
同机运行时长如下
多次运行结果大概稳定在220ms左右
那是不是说明用scanf一定比cin好?
未必,因为曾经在电脑室听高哥说过cin一个神奇的开关
于是乎,我们尝试关掉这个开关来使用cin
1 2 3 4 5 6 7 8 9 10 11 |
#include <cstdio> #include <iostream> using namespace std; int a[1000001]; int main(){ freopen("data.in","r",stdin); std::ios::sync_with_stdio(false); for(int i=1;i<=1000000;i++) cin>>a[i]; return 0; } |
运行时间如下
多次运行耗时稳定在135ms左右,所以在这种情况底下,cin的输入时间看起来更优
能不能再快点??
其实我也这么问过,后来我在某个大佬的博客上看代码学习树剖的时候,偶然间学习到了一个快速读入的操作
经过skida大佬的一番解说,算是有了一点初步的认识,后来也尝试写了几遍
再后来,模拟赛基本都用这个方式写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <cstdio> #include <iostream> using namespace std; int a[1000001]; int getint(){ char c=getchar(); int ans=0; while(c<'0' || c>'9') c=getchar(); while(c>='0' && c<='9'){ ans=ans*10+c-'0'; c=getchar(); } return ans; } int main(){ freopen("data.in","r",stdin); for(int i=1;i<=1000000;i++) a[i]=getint(); return 0; } |
运行时间如下
多次运行结果稳定在75ms左右
结论:耗时和代码长度是呈反比的。
但是在快节奏的生活里,我们应该学会慢下来,喝杯茶静静地等待程序的运行,不要一味的追求更快而失去了探索过程的乐趣。
- 上一篇:【编译原理01】词法分析