How much footprint does C++ exception handling add

后端 未结 8 1239
有刺的猬
有刺的猬 2020-11-28 05:50

This issue is important especially for embedded development. Exception handling adds some footprint to generated binary output. On the other hand, without exceptions the err

8条回答
  •  感动是毒
    2020-11-28 06:06

    Measuring things, part 2. I have now got two programs. The first is in C and is compiled with gcc -O2:

    #include 
    #include 
    
    #define BIG 1000000
    
    int f( int n ) {
        int r = 0, i = 0;
        for ( i = 0; i < 1000; i++ ) {
            r += i;
            if ( n == BIG - 1 ) {
                return -1;
            }
        }
        return r;
    }
    
    int main() { 
        clock_t start = clock();
        int i = 0, z = 0;
        for ( i = 0; i < BIG; i++ ) {
            if ( (z = f(i)) == -1 ) { 
                break;
            }
        }
        double t  = (double)(clock() - start) / CLOCKS_PER_SEC;
        printf( "%f\n", t );
        printf( "%d\n", z );
    }
    

    The second is C++, with exception handling, compiled with g++ -O2:

    #include 
    #include 
    
    #define BIG 1000000
    
    int f( int n ) {
        int r = 0, i = 0;
        for ( i = 0; i < 1000; i++ ) {
            r += i;
            if ( n == BIG - 1 ) {
                throw -1;
            }
        }
        return r;
    }
    
    int main() { 
        clock_t start = clock();
        int i = 0, z = 0;
        for ( i = 0; i < BIG; i++ ) {
            try {
             z += f(i); 
            }
            catch( ... ) {
                break;
            }
    
        }
        double t  = (double)(clock() - start) / CLOCKS_PER_SEC;
        printf( "%f\n", t );
        printf( "%d\n", z );
    }
    

    I think these answer all the criticisms made of my last post.

    Result: Execution times give the C version a 0.5% edge over the C++ version with exceptions, not the 10% that others have talked about (but not demonstrated)

    I'd be very grateful if others could try compiling and running the code (should only take a few minutes) in order to check that I have not made a horrible and obvious mistake anywhere. This is knownas "the scientific method"!

提交回复
热议问题