簡體   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;
}

當我使用cin和cout時,這個程序在hackerearth中超時。 但是通過了 scanf 和 printf。

速度差異主要是由於 iostream I/O 函數與 CI/O 函數保持同步。 我們可以通過調用std::ios::sync_with_stdio(false);來關閉它std::ios::sync_with_stdio(false);

默認情況下,標准 C++ 流在每次輸入/輸出操作后同步到標准 C 流。

一旦關閉同步,C++ 標准流就可以獨立緩沖它們的 I/O,你可以嘗試看看所用的時間幾乎相似(可能小於 scanf)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM