1
votes

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
1
this is C++ code, not C code. Please remove the c taguser3629249
Not sure why you keep saying "cousync_with_stdio"Lightness Races in Orbit
do you understand what is meant by 'synchronous' and by 'asynchronous'? When you specify 'synchronous', then each I.O is completed before the next action is started. I.E. activities are not overlapping I.E. in sequence. This makes everything take much more 'wall clock' time than 'asynchronous' I/O where, when possible, multiple activities are being performed at the same time.user3629249

1 Answers

7
votes

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';