Time difference between stdio. h and iostream

Asked

Viewed 477 times

6

I made two codes so that an online Judge corrected. They are essentially the same. But the with stdio. h is accepted and the with the iostream is not, because it exceeds the time limit. Why this occurs?

#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;
}

The with the 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;
}

1 answer

6


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

You can reduce running time by disabling this Feature with the command:

std::ios_base::sync_with_stdio(false);

In addition to the endl force a flush (see that answer on Quora). In loops \n may turn out to be more efficient (in your case, as you only use cout once the difference is not significant):

cout << min << '\n';

Made the substitutions the example with iostream was on average 13% faster than the example with stdio on my machine / compiler / OS (always be careful generalizing microbenchmarks, but in this case the difference was remarkable).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.