为什么cin/cout比scanf/printf慢 [英] why is cin/cout slower than scanf/ printf

查看:78
本文介绍了为什么cin/cout比scanf/printf慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

int main(){
    int t;
    long long int n,res,x;
    scanf("%d",&t);
    while(t--){
            scanf("%lld",&n);
            res=0;


    for(int i=0;i<n;i++){
            scanf("%lld",&x);
            res^=x;
    }
    if(res==0)
        printf("-1\n");
    else 
        printf("%lld\n",res);

}
return 0;
}

当我使用cin和cout时,同一程序在hackerearth中超时.但是通过scanf和printf传递.

this same program when i used cin and cout was timed out in hackerearth. But passed with scanf and printf.

推荐答案

速度差异很大程度上归因于iostream I/O功能与C I/O功能保持同步.我们可以通过调用 std :: ios :: sync_with_stdio(false);

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);

默认情况下,每次输入/输出操作后,默认的标准C ++流都将同步到标准C流.

By default standard C++ streams are synchronized to the standard C stream after each input/output operation.

关闭同步后,C ++标准流将被允许独立缓冲其I/O,您可以尝试看看所花费的时间几乎相同(可能比scanf短)

Once synchronization is turned off, the C++ standard streams are allowed to buffer their I/O independently, you can try and see the time taken will be almost similar (possibly lesser than scanf)

这篇关于为什么cin/cout比scanf/printf慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆