2

重複の可能性:
C++ どちらが速いか: スタック割り当てまたはヒープ割り当て

TEST を定義して、または定義せずに、次のコードをテストしていました。

#include <cstdlib> // atoi

int main( int argc, char *argv[ ] ) {
    int times = 100000000;

    switch ( argc ) {
        case 2:
          times = atoi( argv[1] );
    } // switch

    volatile int *arr = 0;
    delete arr;

    for ( int i = 0; i < times; i += 1 ) {
    #ifdef TEST
        arr = new int[10];
        arr[0] = 5;
        delete [ ] arr;
    #else
        volatile int arr[10];
        arr[0] = 5;
    #endif
    }
}

以下は私の時間出力です:

$ time ./q1test    // variable TEST defined  
real   0m7.319s  
user   0m7.289s  
sys    0m0.007s  

$ time ./q1notest  // variable TEST not defined  
real   0m0.281s  
user   0m0.276s  
sys    0m0.003s  

$ time ./q1dynopt  // variable TEST defined with compiler optimization
real   0m7.137s  
user   0m7.116s  
sys    0m0.006s  

$ time ./q1nodynopt // variable TEST not defined with compiler optimization
real   0m0.053s  
user   0m0.048s  
sys    0m0.003s  

最初のケースが2番目のケースよりもはるかに遅い理由を知りたいですか? また、コンパイラの最適化が最初のケースに影響しないのはなぜですか?

スタック割り当てとヒープ割り当てが原因であることはわかっていますが、可能であれば、より深く理解したいと思います。

4

0 に答える 0