简体   繁体   English

std::priority_queue 与 std::set 之间的性能差异

[英]Performance difference between std::priority_queue vs std::set

I am testing the performance difference between priority queue implementation of std::priority_queue vs implementation using std::set.我正在测试 std::priority_queue 的优先级队列实现与使用 std::set 的实现之间的性能差异。

I have overloaded the < operator to sort based on score, in case when scores are equal use the next argument i.我已经重载 < 运算符以根据分数进行排序,以防分数相等时使用下一个参数 i。 Also I am just calling the push,pop and top function to find the total time taken for these three operations.此外,我只是调用 push、pop 和 top 函数来查找这三个操作所花费的总时间。

In both implementation I am calling this 'timeQueue' function over 200 iterations and averaging the time obtained.在这两个实现中,我在 200 次迭代中调用这个“timeQueue”函数并平均获得的时间。 I am seeing the std::set implementation takes around 38% faster.我看到 std::set 实现的速度提高了大约 38%。 What could be the reason.可能是什么原因。 Thank you.谢谢你。

(These are just for testing purpose) (这些只是为了测试目的)

std::set implementation std::set实现

void timeQueue()

{
        NodeData res;
        for(int i=1;i<=500000;i++)
        {
                
                auto score = rand() %10000000;
                NodeData n1 = {i,i,score,i,i};
                // push:
                priorityList.insert(n1);
                
        }       
        for(int i=1;i<=500000;i++)
        {       
                std::set<NodeData>::iterator it = priorityList.begin(); 
                // top:
                auto s = it->id;
                // pop:
                priorityList.erase(it);
        }
}

Similarly, std::priority_queue同样, std::priority_queue

void timeQueue()
{
 NodeData res;
        for(int i=1;i<=500000;i++)
        {
                auto score = rand() % 10000;
                NodeData n1 = {i,1,score,1,1};
                priorityList.push(n1);
        }
        for(int i=1;i<=500000;i++)
        {
                res = priorityList.top();
                priorityList.pop();
                //std::cout<<res.id<<std::endl; 
        }
}
};

I think the reason for this performance difference is in set the elements are randomly generated and if by chance the generated elements are not unique, they are not inserted.我认为这种性能差异的原因在于,元素是随机生成的,如果偶然生成的元素不是唯一的,则不会插入它们。 Hence in effect, the std::set will have lesser elements than the std::priority_queue.因此实际上,std::set 的元素将少于 std::priority_queue。 And so lesser execution time.因此执行时间更短。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM