[英]why is cin/cout slower than 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;
}
this same program when i used cin and cout was timed out in hackerearth.当我使用cin和cout时,这个程序在hackerearth中超时。 But passed with scanf and printf.但是通过了 scanf 和 printf。
The speed difference is largely due to the iostream I/O functions maintaining synchronization with the CI/O functions.速度差异主要是由于 iostream I/O 函数与 CI/O 函数保持同步。 We can turn this off with a call to std::ios::sync_with_stdio(false);
我们可以通过调用std::ios::sync_with_stdio(false);
来关闭它std::ios::sync_with_stdio(false);
By default standard C++ streams are synchronized to the standard C stream after each input/output operation.默认情况下,标准 C++ 流在每次输入/输出操作后同步到标准 C 流。
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)一旦关闭同步,C++ 标准流就可以独立缓冲它们的 I/O,你可以尝试看看所用的时间几乎相似(可能小于 scanf)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.