论几种在C++中可行的输入的速度

关于几种在C++中都可行的输入比较:

1.“传统”的cin

在文件中读取1000000个数——

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int d;
int main(){
    freopen("ch.in","r",stdin);
    for(int i=1;i<=1000000;i++) cin>>d;
    return 0;
}
Process exited after 0.5594 seconds with return value 0

为什么比较慢?其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销!

2.“改良”的cin

在文件中读取1000000个数——

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int d;
int main(){
    freopen("ch.in","r",stdin);
    std::ios::sync_with_stdio(false);//加速“神功”
    for(int i=1;i<=1000000;i++) cin>>d;
    return 0;
}
Process exited after 0.1438 seconds with return value 0

哇!快了许多!这样就可以取消cin与stdin的同步了。

3.C语言的scanf

在文件中读取1000000个数——

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int d;
int main(){
    freopen("ch.in","r",stdin);
    for(int i=1;i<=1000000;i++) scanf("%d",&d);
    return 0;
}
Process exited after 0.4145 seconds with return value 0

竟然比升级版的cin还慢!

3.自治快读“read”

在文件中读取1000000个数——

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int d;
inline int read(){
    int s=0,w=1;
    char ch=getchar();
    while(ch<='0'||ch>'9'){
        if(ch=='-') w=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
    return s*w;
}
int main(){
    freopen("ch.in","r",stdin);
    for(int i=1;i<=1000000;i++) d=read();
    return 0;
}
Process exited after 0.09868 seconds with return value 0

无敌王者啊!

============================================================================================

最后的排名

1.read();
2.cin升级版
3.scanf();
4.cin普通版

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值