随附时,可笑地慢慢删除调试器(MSVC)
-
12-12-2019 - |
题
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类是不宽泛的速度。结果机代码相当优化,因此我不希望它是编译器问题而不是调试器,但我不知道如何处理它。我的问题是
- 是你机器上的这个问题吗?
- 这种行为的原因是什么?
- 有没有解决方法?
解决方案
减速是由内存检查引起的,每当存储器被释放时发生。但是,这是一个特殊的系统/调试器级堆,而不是您可以从程序中控制的任何内容。
有一个很棒的文章问题。总结:您必须设置一个环境变量以禁用它!
幸运的是,您可以从项目设置的项目设置中的调试选项中设置特定于项目的环境变量,以便环境变量仅应用于您的程序。
我使用了这个简化的程序来测试:
#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
设置为环境变量(系统范围,我不会推荐的,或通过调试选项),代码在大致相同的时间内运行,而不管是否连接调试器。
不隶属于 StackOverflow