i++ less efficient than ++i, how to show this?

前端 未结 9 1838
暖寄归人
暖寄归人 2020-12-03 14:30

I am trying to show by example that the prefix increment is more efficient than the postfix increment.

In theory this makes sense: i++ needs to be able to return the

9条回答
  •  渐次进展
    2020-12-03 14:51

    In response to Mihail, this is a somewhat more portable version his code:

    #include 
    #include 
    using namespace std;
    
    #define SOME_BIG_CONSTANT 100000000
    #define OUTER 40
    int main( int argc, char * argv[] ) {
    
        int d = 0;
        time_t now = time(0);
        if ( argc == 1 ) {
            for ( int n = 0; n < OUTER; n++ ) {
                int i = 0;
                while(i < SOME_BIG_CONSTANT) {
                    d += i++;
                }
            }
        }
        else {
            for ( int n = 0; n < OUTER; n++ ) {
                int i = 0;
                while(i < SOME_BIG_CONSTANT) {
                    d += ++i;
                }
            }
        }
        int t = time(0) - now;  
        printf( "%d\n", t );
        return d % 2;
    }
    

    The outer loops are there to allow me to fiddle the timings to get something suitable on my platform.

    I don't use VC++ any more, so i compiled it (on Windows) with:

    g++ -O3 t.cpp
    

    I then ran it by alternating:

    a.exe   
    

    and

    a.exe 1
    

    My timing results were approximately the same for both cases. Sometimes one version would be faster by up to 20% and sometimes the other. This I would guess is due to other processes running on my system.

提交回复
热议问题