Using scanf() in C++ programs is faster than using cin? -


I do not know if this is true, but when I was asking often on one of the problems in providing sites, I found some that got my attention:

Check your input / output methods In C ++, use of cin and cout is very slow. Use these, and you will be guaranteed not to be able to solve any problem in which there will be input or output in good quantity, instead use printf and scanf.

Can anyone explain it? Is scanf () faster than using cin >> something in C ++ programs? If so, is it a good practice to use in the C ++ program? I thought it was special, although I'm just learning C ++ ...

here A quick test is a simple case: A program to read the list of numbers from standard input and XOR numbers.

iostream version:

  Include # lt; Iostream & gt; Int main (int argc, char ** argv) {int parity = 0; Int x; While (std :: cin> gt; x) parity ^ = x; Std :: cout & lt; & Lt; Parity & lt; & Lt; Std :: endl; Return 0; }  

scanf version:

  #include & lt; Stdio.h & gt; Int main (int argc, char ** argv) {int parity = 0; Int x; While (1 == scanf ("% d", & amp; x)) equality ^ = x; Printf ("% d \ n", similarity); Return 0; }  

Result

Using the third program, I have generated a text file with a random number of 33,280,276. Performance time:

  iostream version: 24.3 seconds scanning version: 6.4 seconds  

Changing the optimization settings of the compiler does not seem to result too much.

Thus: There is actually a speed difference.


Edit: The speed difference between the user clyfish that is largely due to iostream is the I / O function which maintains synchronization with the CI / O functions we call it Std :: IOS :: sync_with_stdio (wrong) can close with the call; :

  #include & lt; Iostream & gt; Int main (int argc, char ** argv) {int parity = 0; Int x; Std :: ios :: sync_with_stdio (wrong); While (std :: cin> gt; x) parity ^ = x; Std :: cout & lt; & Lt; Parity & lt; & Lt; Std :: endl; Return 0; Iostream version: 21.9 seconds scanf version: iStream 6.8 seconds with sync_with_stdio (wrong):  

New result:

 5.5 seconds  

win C + iostream! It has come to know that it is internal sync / flushing that usually slows iostream i / o if we are not mixing CSTDO and iOstream, then we can turn it off, and then iostream most It's fast.

Code:


Comments

Popular posts from this blog

c++ - Linux and clipboard -

Visual Studio 2005: How to speed up builds when a VSMDI is open? -

booting ubuntu from usb using virtualbox -