2012-11-27 61 views
6

這段代碼在我的VS2012中大約需要20秒,但在G ++中只需要1.x秒。 都在win8 x64和編譯與默認選項。爲什麼在VC++中list :: push_back比g ++慢得多

list<double> items; 
for(int i=0;i<10000000;i++){ 
    items.push_back(rand()); 
} 
cout<<"done"<<endl; 

這是關於內存分配的東西嗎?在我的機器上使用VC++輸出後,釋放內存需要3〜5秒鐘,並且在我的firend(win7 x64)中甚至超過1分鐘。

+22

我不確定G ++的默認構建配置是什麼,但是對於Visual Studio它是** DEBUG **,並且您不想比較調試構建的性能 – emartel

+0

如何使用VS中的Release進行編譯以及-O2 gcc選項? – nhahtdh

+1

您是否嘗試在循環之前執行'items.reserve(10000000)'? – 2012-11-27 15:45:26

回答

12

嗯...我擴大你的代碼,包括計時:

#include <list> 
#include <iostream> 
#include <time.h> 
#include <stdlib.h> 

int main() { 
    std::list<double> items; 

    clock_t start = clock(); 

    for(int i=0;i<10000000;i++){ 
     items.push_back(rand()); 
    } 

    clock_t finish = clock(); 

    std::cout << "Time: " << double(finish-start)/CLOCKS_PER_SEC << "\n"; 
    return 0; 
} 

我用用VC++編譯:cl /O2b2 /GL test_list.cpp

同樣,我與G ++編譯,使用:g++ -O3 test_list.cpp

然後我跑了兩個。

用VC++得到:Time: 1.293
用g ++我得到了:Time: 1.313

這是一個足夠小的差異,我認爲我需要測試相當多的是說VC++顯著生產更快代碼的完全肯定,但我認爲這是足以支持一個結論,即VC++是不是顯着產生較慢代碼。

您需要打開時序結果的優化才能表示任何內容。

+0

謝謝。我的代碼幾乎是這樣的。該問題的DEBUG compling選項。 – raulchen

+4

@raulchen Debug *表示*表示速度很慢,因此可以*調試*。 – Mysticial

+2

@Mystical * *的意思是選擇「嘈雜」的錯誤來通知開發人員潛在的問題,而不是執行適合現場部署的處理。 99%的時間會比較慢,但發佈版本肯定可以自由地以較慢的方式對意外情況做出反應。我提到的部分原因是我實際上*不相信調試/發佈的區別*(!),斷言或驗證:http://hostilefork.com/hoist/ – HostileFork

-4

如果您在Windows上並擔心性能,請勿使用STL容器。功能相當的ATL容器類通常更快

在我的筆記本電腦上(i5-2410M CPU,Windows 7 64),您的示例(在用Visual Studio 2010 for 64位編譯版本時)在740毫秒內執行。當使用功能相當的ATL容器CAtlList<double>時,執行時間下降到370毫秒。

與微軟的高級函數庫相比,使用標準函數庫的性能損失約爲50%。

這裏的源代碼:

void list_stl() 
{ 
    std::list<double> items; 
    CBenchmarkTimer tt("10M doubles in std::list"); 
    for(int i = 0; i < 10000000; i++) 
     items.push_back(rand()); 
    tt.End(); 
} 

void list_atl() 
{ 
    CAtlList<double> items; 
    CBenchmarkTimer tt("10M doubles in CAtlList"); 
    for(int i = 0; i < 10000000; i++) 
     items.AddTail(rand()); 
    tt.End(); 
} 

CBenchmarkTimer是我自己的類,它使用高分辨率計時器。

+1

我懷疑它們在功能上是否相當快,但我也懷疑它的速度要快得多...... –

+3

C++標準庫到底是「開放源代碼」? – fredoverflow

+0

@MooingDuck,我已經添加了源代碼 - 如果您有疑問,請隨時測試自己。是的,它們在功能上是等效的,請參閱CAtlList的文檔。 – Soonts

相關問題