2012-05-21 17 views
7
struct test_struct 
{ 
    test_struct() {} 
    ~test_struct() {} 
}; 

#include <vector> 
#include <memory> 
#include <cstdio> 

int main() 
{ 
    printf("ctor begin\n"); 
    { 
     std::vector<std::unique_ptr<test_struct>> test_vec; 
     const int count = 100000; 

     for (auto i = 0; i < count; i++) { 
      test_vec.emplace_back(new test_struct); 
     } 
     printf("dtor begin\n"); 
    } 
    printf("dtor end\n"); 
} 

我正在使用VS2010,並發現了一些荒謬的性能問題。上面的代碼在調試和發佈版本(ctrl + f5)中都能很好地工作,但是當調試器連接(f5)時,dtor調用unique_ptr類的速度變得難以忍受。結果機器代碼是相當優化的,所以我不認爲它是編譯器問題而不是調試器的問題,但我不知道如何處理它。我的問題是連接調試器時,可笑地減慢unique_ptr dtor調用(msvc)

  • 此問題是否可以在您的計算機上重現?
  • 這種行爲的原因是什麼?
  • 有沒有解決方法?
+0

在每次printf後嘗試刷新。 – Pubby

+0

@Pubby:這不會有什麼區別,只有3個'printf'總數,每個循環迭代都不會有一個。 –

+0

我能夠在我的VS2010快速版上重現這一點。 – RedX

回答

6

減速是由內存檢查導致的,每當內存被釋放時都會發生。但是,這是一個特殊的系統/調試器級別的堆,不是您可以在程序中控制的任何東西。

有一個great article on the issue。總結一下:你必須設置一個環境變量來禁用它!

幸運的是,您可以從項目的項目設置的「調試」選項中設置項目特定的環境變量,以便環境變量僅應用於您的程序。

我用該簡化的程序進行測試:

#include <iostream> 
#include <memory> 
#include <vector> 

int main() 
{ 
    std::cout << "ctor begin" << std::endl; 
    { 
     std::vector<std::unique_ptr<int>> test_vec; 

     for (unsigned i = 0; i < 100000; i++) 
      test_vec.emplace_back(new int); 

     std::cout << "dtor begin" << std::endl; 
    } 
    std::cout << "dtor end" << std::endl; 
} 

通過設置_NO_DEBUG_HEAP=1作爲環境變量(或者系統範圍的,在此不推薦,或者通過調試選項),則代碼在運行大致相同的時間量,不管調試器是否連接。