Faster input and output

后端 未结 2 1932
渐次进展
渐次进展 2021-01-29 15:37
#include
using namespace std;
int main(){
    int i,x,max=0;
    cin>>x;
    int a[x];
    for(i=0;i>a[i];
        if         


        
相关标签:
2条回答
  • 2021-01-29 15:47

    I'm pretty certain your code is problematic because you are using cout << x << endl; in a loop that will print a huge number of lines.

    I will be back with "difference" in a few minutes.

    Edit: Not sure I can make much of a difference either way. Obviously, depending on compiler, it may vary greatly, but with my g++ -O2 and 100000 input numbers, it takes 0.16 - 0.18s to use endl; and 0.06 - 0.07s to use '\n' for the output.

    Using printf isn't faster than cout, but scanf is a little faster than cin (0.04s +/- 0.05).

    However, that is really related to sync_with_stdio. If we use cin.sync_with_stdio(false); then the results are the same for scanf and cin.

    All measurements are made with a file as input and a file as output - it takes much longer to write to the shell, but that's because it's scrolling 100k lines of text past me.

    (Your program will crash with eithr "large" inputs or with large number of inputs - if max is greater than about 1 million, the code will crash due to out of stack - on many systems, that may happen for lower values too)

    0 讨论(0)
  • 2021-01-29 15:54

    Avoid cin and cout, and use the C IO functions scanf and printf instead. You'll find they can be up to 5x faster than the slow c++ functions.

    0 讨论(0)
提交回复
热议问题