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

后端 未结 15 2830
旧时难觅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:16

    To settle this:

    #include 
    #include 
    #include 
    using namespace std;
    
    int main( int argc, char * argcv[] ) {
        const char * const s1 = "some text";
        const char * const s2 = "some more text";
        int x = 1, y = 2, z = 3;
        const int BIG = 2000;
        time_t now = time(0);
        for ( int i = 0; i < BIG; i++ ) {
            if ( argc == 1 ) {
                cout  << i << s1 << s2 << x << y << z << "\n";
            }
            else {
                printf( "%d%s%s%d%d%d\n", i, s1, s2, x, y, z );
            }
        }
        cout << (argc == 1 ? "cout " : "printf " ) << time(0) - now << endl;
    }
    

    produces identical timings for cout and printf.

提交回复
热议问题