Reputation: 149
I just know using cin and cout will be slower than scanf and printf. However, the top answer says using std::ios::sync_with_stdio(false) can be faster than scanf&printf. However, I did this experiment and found it wasn't right. Is it my fault? Why?
What is a right code to use cin&cout faster than scanf&printf including reading files. Thanks.
Here is my code:
Generating data
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
FILE *data = freopen("test.in","w",stdin);
//FILE *fi = freopen("test.in","r",stdin);
//FILE *fo = freopen("test.out","w",stdout);
int main()
{
for(int i=1;i<10000000;i++)
printf("%d\n",i);
return 0;
}
Using scanf&printf
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
//FILE *data = freopen("test.in","w",stdin);
FILE *fi = freopen("test.in","r",stdin);
FILE *fo = freopen("test.out","w",stdout);
int main()
{
int ans = 1;
while(~scanf("%d",&ans))
{
printf("%d\n",ans);
}
return 0;
}
Using cin & cout ( std::ios::sync_with_stdio(true) )
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
//FILE *data = freopen("test.in","w",stdin);
FILE *fi = freopen("test.in","r",stdin);
FILE *fo = freopen("test.out","w",stdout);
int main()
{
std::ios::sync_with_stdio(true);
int ans = 1;
while(std::cin>>ans)
{
std::cout<<ans<<std::endl;
}
return 0;
}
Using std::ios::sync_with_stdio(false)
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
//FILE *data = freopen("test.in","w",stdin);
FILE *fi = freopen("test.in","r",stdin);
FILE *fo = freopen("test.out","w",stdout);
int main()
{
std::ios::sync_with_stdio(false);
int ans = 1;
while(std::cin>>ans)
{
std::cout<<ans<<std::endl;
}
return 0;
}
Result:
scanf version: 4.918 seconds
iostream version: 51.266 seconds
iostream with sync_with_stdio(false): 31.815 seconds
Upvotes: 1
Views: 2509
Reputation: 385102
You're flushing std::cout
every single time, with std::endl
.
Don't do that. Instead, just output a '\n'
if you want to match the behaviour of the printf
version:
std::cout << ans << '\n';
Upvotes: 7