Difference in runtime between stdio.h e iostream
I made two codes for an online judge to correct. They are essentially the same. But the with stdio.h is accepted and O with iostream is not, as it exceeds the timeout. 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;
}
1 answers
cin
and cout
"spend" a good amount of time synchronizing with the buffers of the 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 runtime by disabling this feature with the command:
std::ios_base::sync_with_stdio(false);
Additionally endl
Forces a flush (see this answer in Quora ). In loops \n
can become 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 noticeable).