Difference in execution time between stdio.h and iostream

6

I made two codes for an online judge to correct. They are essentially the same. But the stdio.h is accepted and the with the iostream does not, because it exceeds the time limit. Why does this occur?

#include <stdio.h>
int tipo[1000000];
int main(){
    int qtdrot, qtdtipos, i, x, min;
    scanf("%d%d", &qtdrot, &qtdtipos);
    for(i=0; i<qtdrot; ++i){
        scanf("%d", &x);
        tipo[x]++;
    }
    min=1000000;
    for(i=1; i<=qtdtipos; i++){
        if(tipo[i]<min)min=tipo[i];
    }
    printf("%d\n", min);
    return 0;
}

O with iostream:

#include <iostream>
using namespace std;
int tipo[1000000];
int main(){
    int qtdrot, qtdtipos, i, min, t;
    cin>>qtdrot>>qtdtipos;
    for(i=0; i<qtdrot; ++i){
        cin>>t;
        tipo[t]++;
    }
    min=1000000;
    for(i=1; i<=qtdtipos; i++){
        if(tipo[i]<min)min=tipo[i];
    }
    cout<<min<<endl;
    return 0;
}
    
asked by anonymous 02.03.2016 / 08:51

1 answer

6

cin and cout "spend" a good amount of time synchronizing with buffers of stdio . It is not difficult to see programs with 3-4 times slower operations compared to scanf and printf (see this example in SOEn ).

You can reduce the runtime by disabling this feature with the command:

std::ios_base::sync_with_stdio(false);

In addition,% w / w forces flush (see this answer in Quora ). In loops endl can be more efficient (in your case, since you only use \n because the difference is not significant):

cout << min << '\n';

With the replacements the example with cout was on average 13% faster than the example with iostream on my machine / compiler / OS (always be careful about generalizing microbenchmarks , but in that if the difference was remarkable).

    
02.03.2016 / 12:22