关于printf/scanf 与 cin/cout 输入输出的速度研究

这是我的第一篇研究型博客……
好吧,步入正题。
我们经常听别人说:cin/cout 输入输出慢,printf/scanf 大法好,那么 cin/cout 究竟有多慢?
为此我写了一个数据生成器,其实就是生成了 1-5000000 的一个递增序列,生成的文件大小有38.9 MB (38,888,896 字节)。
现在有两个程序干同一件事:把这个文件输入,原样输出,但一个是 cin/cout,一个是 printf/scanf。

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
    int x;
    for(int i=1;i<=5000000;++i)
    {
        scanf("%d",&x);
        printf("%d",x);
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
    int x;
    for(int i=1;i<=5000000;++i)
    {
        cin>>x;
        cout<<x;
    }
    fclose(stdin);
    fclose(stdout);
}

可以看出,两则程序除了输入输出之外,没有什么区别。
但它们分别运行了多久呢?
我们用Linux下的time命令测时间。
time命令:http://baike.baidu.com/subview/10368/12526581.htm
结果如何呢?
printf/scanf 与 cin/cout
呵呵……显而易见,当然是 printf/scanf 更快啦。
不过,传说中取消 cin/cout 与 stdio 的同步以后会更快,差不多与 printf/scanf 相当,我们来试一试!

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);//这两行语句取消了同步
    cin.tie(0);                 //和其他占时间的因素。
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
    int x;
    for(int i=1;i<=5000000;++i)
    {
        cin>>x;
        cout<<x;
    }
    fclose(stdin);
    fclose(stdout);
}

cin/cout syncfalse
看吧!的确是差不多了。
注意: 取消同步后,不要在程序里再使用 printf/scanf 等 cstdio 中的输入输出(文件操作除外)!否则后果……
就先研究这么多,我要去复习了:http://blog.csdn.net/Zn_Hua/article/details/53437724
参考:http://www.hankcs.com/program/cpp/cin-tie-with-sync_with_stdio-acceleration-input-and-output.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值