2013-09-27 33 views
0

我剛剛寫了一個小小的C++程序,目的是爲了理解向量如何處理內存以及運行時發生了什麼。C++向量內存分配和運行時?

有我的代碼:

#include <iostream> 
#include <cstdio> 
#include <ctime> 
#include <vector> 

int main(){ 

    clock_t start, end; 

    int x; 

    std::vector<int> a(5, 100); 

    start = clock(); 

    for(int i = 0 ; i <= 900000000 ; i++){ 
     x = a[0]; 
     x = a[1]; 
     x = a[2]; 
     x = a[3]; 
     x = a[4]; 
    } 

    end = clock(); 

    clock_t duration = end - start; 

    double durationPerSec = duration/(double)CLOCKS_PER_SEC; 

    std::cout << "Run-time : " << durationPerSec << std::endl; 

    return 0; 
} 

,我得到這樣的輸出:

運行時間:18.7843

當我通過更換矢量編寫相同的代碼動態數組的運行時間更可接受:

運行時間:2.9526

我知道這個代碼是相當愚蠢的,但我不知道爲什麼運行時間如此之長,當我使用的載體?那是因爲我以錯誤的方式使用它,還是因爲有些東西我不明白?

感謝您的回覆。

+0

什麼是你提到這個 「動態數組」? –

+2

您是否正在運行優化版本? – juanchopanza

+0

可能重複的[std :: vector比普通數組慢很多?](http://stackoverflow.com/questions/3664272/stdvector-is-so-much-slower-than-plain-arrays) – delnan

回答

1

g++ -O0 a.cc運行它,並獲得

Run-time : 18.99 

但是,如果使用g++ -O2 a.cc

Run-time : 0 

更開動,我跑了第二,time ./a.out

time ./a.out 
Run-time : 0 

real 0m0.009s 
user 0m0.002s 
sys  0m0.002s 

我改變循環到

for(int i = 0 ; i <= 900000000 ; i++){ 
    a[0] = i ; 
    a[1] = i + a[0]; 
    a[2] = a[1] + a[2]; 
    a[3] = i + a[1] + a[2]; 
    a[4] = i + a[1] + a[2] + a[3]; 
    x = a[0]; 
    x = a[1]; 
    x = a[2]; 
    x = a[3]; 
    x = a[4]; 
} 

隨後的g++ -O2結果是

time ./a.out 
Run-time : 1.81 

real 0m1.817s 
user 0m1.811s 
sys  0m0.001s 
+0

是的,但它可能是整個循環現在被優化了嗎?它會給我一個[i] = i;在循環內或類似的東西? –

+0

你是對的,讓我試試看。 –

+0

g ++ -02和g ++ - O0之間的區別是什麼? – FlorentinTh

0

您應該在啓用優化的情況下進行測量。

operator[]是一個成員函數。當你使用[0]訪問元素時,它實際上是通過一個函數來完成的,所以有更多的指令可以執行,儘管符號相同。在調試中,會有可測量的開銷。在發佈時,它通常是不可測量的。