简体   繁体   English

为什么 cin/cout 比 scanf/ printf 慢

[英]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.

相关问题 在这种情况下,为什么“ printf scanf”比“ cout cin”慢? - Why do “printf scanf” is slower than “cout cin” in this case? 从printf scanf转换为cin cout的问题 - Problems converting from printf scanf to cin cout 何时使用 printf/scanf 与 cout/cin? - When to use printf/scanf vs cout/cin? 为什么使用putchar_unlocked的此方法比printf和cout的打印字符串要慢? - Why this method using putchar_unlocked is slower than printf and cout to print strings? printf/scanf的用法和区别<iostream>和 cout/cin 的区别,什么时候用哪个?</iostream> - printf/scanf usage and difference from <iostream> and cout/cin diffferences, when to use which? cout/cin 是否在内部调用 printf() / scanf() 就像 `new` 调用 malloc? - Does cout/cin internally call printf() / scanf() like `new` calls malloc? 使用 scanf 和 printf 使程序无限循环,但通过替换为 cin 和 cout 工作正常 - using scanf and printf makes the program infinite loop but by replacing with cin and cout works ok 为什么 cout 和 cin 使用按位移位(&lt;&lt; 和 &gt;&gt;)? - Why are bitwise shifts (<< and >>) used for cout and cin? 如何cout比printf()更安全类型 - How cout is more typesafe than printf() 为什么printf()在C ++指针中显示与cout不同的地址输出? - Why does printf() display a different address output than cout in C++ pointers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM