【问题标题】:why is cin/cout slower than scanf/ printf为什么 cin/cout 比 scanf/printf 慢
【发布时间】:2017-06-02 14:25:09
【问题描述】:
#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。

【问题讨论】:

  • 标准答案:试试std::ios::sync_with_stdio(false);
  • std::cout &lt;&lt; std::endl; 正在做flush()。使用std::cout &lt;&lt; '\n'; 并再次检查时间。
  • ostream/istream 与 printf/scanf 有一个共同点,那就是它们都是非常慢且开销很大的函数。您不应该假设其中任何一个都很快,也不能轻易知道在给定场景下 ostream 实现是比 printf 快还是慢。
  • @Nick 虽然我同意避免使用std::endl,但cout 通常是行缓冲的。虽然在这种情况下可能不是,但这取决于hackerearth 如何处理输出。

标签: c++ c++11 c++14


【解决方案1】:

速度差异主要是由于 iostream I/O 函数与 C I/O 函数保持同步。我们可以通过致电 std::ios::sync_with_stdio(false); 来关闭它

默认情况下,标准 C++ 流在每次输入/输出操作后同步到标准 C 流。

一旦关闭同步,C++ 标准流就可以独立缓冲它们的 I/O,你可以试试看所花费的时间会差不多(可能小于 scanf)

【讨论】:

    猜你喜欢
    • 2011-12-08
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2015-12-16
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多