【发布时间】:2016-03-17 07:52:52
【问题描述】:
为什么std::queue 中的析构函数非常慢?看看我的例子:
void test()
{
int total = 17173512;
std::queue<int> q;
for(int i = 0; i < total; i++)
q.push(i); //Push is very fast.
std::cout<<"Done"<<std::endl; //Less than a second.
}
test();
std::cout<<"Done"<<std::endl; //This takes several minutes!!
std::vector 中的析构函数非常快...
更新: 我的编译器/IDE 是 Visual Studio 2012 Visual C++。
int main(int argc, char **argv)
{
int total = 17173512;
std::queue<int> q;
for(int i = 0; i < total; i++)
q.push(i);
std::cout<<"Done0"<<std::endl; //This takes less than a second.
while(!q.empty())
q.pop();
//This takes less than a second. Memory should be deallocated here!
std::cout<<"Done1"<<std::endl;
//Waiting forever, i.e. deallocating(HERE??) memory EXTREMELY SLOWLY.
//I can see how the memory is being deallocated here in windows task manager!
return 0;
}
带矢量:
int main(int argc, char **argv)
{
int total = 17173512;
std::vector<int> q(total);
for(int i = 0; i < total; i++)
q[i] = 2000;
std::cout<<"Done"<<std::endl;
return 0; //Extremely fast.
}
更新 2:
现在一切都解决了!我卸载了 Visual Studio 2012 + Visual C++。我已经安装了 Visual Studio Community 2015,一切都比预期的要快得多!
【问题讨论】:
-
有趣。你能粘贴一个完整的程序来演示这个吗?
-
您是否在打开优化的情况下进行编译?另外,您使用的是哪个 c++ 实现?
-
即使使用
-O0,对我来说也只需不到一秒钟。 -
您必须向我们提供有关编译器/系统/实现和上下文的更多信息。在我的 2009 macbook pro 中使用 clang 并使用 -O0 我可以在 1486 毫秒内运行您的代码,对于如此庞大的队列来说这根本不是很多。使用 -O3 我得到 150 毫秒。
-
另外,你应该和
std::deque<int>比较,这是队列内部使用的。
标签: c++ performance queue destructor