cout or printf which of the two has a faster execution speed C++?

后端 未结 15 2865
旧时难觅i
旧时难觅i 2020-11-27 07:04

I have been coding in C++ for a long time. I always wondered which has a faster execution speed printf or cout?

Situation: I am designing a

15条回答
  •  误落风尘
    2020-11-27 07:24

    Each has its own overheads. Depending on what you print, either may be faster.

    Here are two points that come to mind -

    printf() has to parse the "format" string and act upon it, which adds a cost.
    cout has a more complex inheritance hierarchy and passes around objects.

    In practice, the difference shouldn't matter for all but the weirdest cases. If you think it really matters - measure!

    EDIT -
    Oh, heck, I don't believe I'm doing this, but for the record, on my very specific test case, with my very specific machine and its very specific load, compiling in Release using MSVC -

    Printing 150,000 "Hello, World!"s (without using endl) takes about -
    90ms for printf(), 79ms for cout.

    Printing 150,000 random doubles takes about -
    3450ms for printf(), 3420ms for cout.

    (averaged over 10 runs).

    The differences are so slim this probably means nothing...

提交回复
热议问题