C++ cout printing slowly

前端 未结 8 2086
情深已故
情深已故 2020-11-30 14:23

I noticed if I print out a long string(char*) using cout it seems to print 1 character at a time to the screen in Windows 7, Vista, and Linux(using putty) using Visual C++ 2

8条回答
  •  臣服心动
    2020-11-30 14:37

    I would suggest you try this same test on a different computer. I don't have a good answer for why this might be happening; all I can say is I have never noticed a speed difference between cout and printf. I also tested your code using gcc 4.3.2 on Linux and there was no difference whatsoever.

    That being said, you can't easily replace cout with your own implementation. The fact is, cout is an instance of std::ostream which has a lot of functionality built into it which is necessary for interoperability with other classes that overload the iostream operators.

    Edit:

    Anyone that says printf is always faster than std::cout is simply wrong. I just ran the test code posted by minjang, with gcc 4.3.2 and the -O2 flag on a 64-bit AMD Athlon X2, and cout was actually faster.

    I got the following results:

    printf: 00:00:12.024
    cout:   00:00:04.144
    

    Is cout always faster than printf? Probably not. Especially not with older implementations. But on newer implementations iostreams are likely to be faster than stdio because instead of parsing a format string at runtime, the compiler knows at compile time what functions it needs to call in order to convert integers/floats/objects to strings.

    But more importantly, the speed of printf versus cout depends on the implementation, and so the problem described by the OP is not easily explicable.

提交回复
热议问题