c++ - std::queue 析构函数慢得要死,bug?

标签 c++ performance queue destructor

<分区>

为什么 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;
}

用 vector :

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,一切都快多了,并且按预期工作!

最佳答案

我已经使用这段代码来衡量:

int main(){
    auto test = [](){
        auto start = std::chrono::system_clock::now();
        int total = 17173512;
        std::queue<int> q;
        for (int i = 0; i < total; i++){
            q.push(i); //Push is very fast.
        }
        auto end = std::chrono::system_clock::now();
        return end - start;
    };

    auto start = std::chrono::system_clock::now();

    auto pushing_time = test();

    auto end = std::chrono::system_clock::now();
    auto deleting_time = (end - start) - pushing_time;

    std::cout << "Pushing Time:" << pushing_time.count() << '\n';
    std::cout << "Deleting Time:" << deleting_time.count() << '\n';
    return 0;
}

环境:

  • 英特尔 i7-4510U @ 2.00 GHz
  • Windows 8.1
  • MSVS 2013

结果:

Release模式,\O2,附加到 VS:

Pushing Time:71403190

Deleting Time:5293067027

Release模式,\O2,未附加到 VS:

Pushing Time:3743267

Deleting Time:1741230

因此,从结果来看,我怀疑您是否正在将它附加到某个 IDE 上运行。

关于c++ - std::queue 析构函数慢得要死,bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36054496/

相关文章:

c++ - 原始套接字混杂模式不嗅探我写的东西

c++ - 当检查单元格是否被占用时 CLI/C++ 俄罗斯方 block block 崩溃 MSVisualStudio 2008

c++ - 带队列 LNK2005 错误的链表

c++ - C++中的函数重载与数字的数据类型

c# - 为 C++ 类的复杂系统创建 C# 绑定(bind)?

python - 优化大量数据的搜索和插入操作

c# - 使用大文档时运行正则表达式非常慢

mysql - 这个MySQL索引会提高性能吗?

delphi - 在 Delphi 的 Tqueue 中存储记录指针的正确方法是什么

c# - Queue<T> 线程安全 : one writer, 一个读者