Iostream is slow ??

Source: Internet
Author: User

Here, I have to correct the idea that iostream is very slow.
We have observed that iostream is slow, usually because C ++ needs to maintain compatibility with C's Io library, so c ++'s Io library does not have a buffer, it must contain one character and one character!
For example, some people have such a pain point:
Getline (CIN, S );
Scanf ("% d", & I );
In this case, Getline can only read one character at a time. If it reads 100 characters at a time, it only uses 10 characters. The remaining 90 characters cannot be put back in stdin, in this case, the scanf is read from the wrong location. Therefore, to be compatible with C, the C ++ library has to read a single character. In this way, the iostream of C ++ is slow.
Fortunately, this behavior can be set. Cin. sync_with_stdio (false); this will make the iostream of C ++ faster. Of course, if you do this, you must ensure that the C Io library is not used.
The following is a test:
[Xxx @ YYY ~] $ Cat testcio. C & gcc-O3 testcio. C-o testcio. Out
# Include <stdio. h>

Int main (INT argc, char ** argv)
{
Char s [1024];
While (fgets (S, 1024, stdin ))
{
Printf ("% s", S );
}
}

[Xxx @ YYY ~] $ Cat testcxxio. cpp & G ++-O3 testcxxio. cpp-O testcxxio. Out
# Include <iostream>
Using namespace STD;

Int main (INT argc, char ** argv)
{
Cin. sync_with_stdio (false );
Char s [1024];
While (CIN. Getline (S, 1024, '\ n '))
Cout <S <Endl;
}

[Xxx @ YYY ~] $ Time for (I = 0; I <10; I ++); do./testcio. Out <some_text; done
...........
Real 0m7. 170 s
User 0m0. 957 s
Sys 0m1. 623 s

[Xxx @ YYY ~] $ Time for (I = 0; I <10; I ++); do./testcxxio. Out <some_text; done
...........
Real 0m7. 123 S
User 0m0. 742 s
Sys 0m1. 737 s

The speed is the same.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.