1. 程式人生 > >小根堆stl之priority_queue很慢?

小根堆stl之priority_queue很慢?

stl中priority_queue底層是二叉堆實現,但是我自己實現了一個二叉堆,測試速度竟然比priority快好多倍,不知道為什麼?

執行100次,每次push1000個數,pop1000個數

執行結果:

自己的執行時間:62ms

stl中priority_queue執行時間:74272

測試程式碼如下:

(1)實現最小堆的程式碼:

“BiHeap.h”:

#define INITNUM 100
#define TIME 100

#pragma once
#include <assert.h>

template<class T>
class BiHeap
{
public:
BiHeap();
~BiHeap();
private:
T *arry;
int size;
int len;
public:
T top();
void push(T push_value);
void pop();
};

template<class T>
BiHeap<T>::BiHeap()
{
arry = new T[INITNUM];
len = 0;
size = INITNUM;
}

template<class T>
BiHeap<T>::~BiHeap()
{
delete []arry;
}

template<class T>
void BiHeap<T>::pop()
{
if (len == 0)
{
return;
}
T temp = arry[len];
int null_node_position = 1;
int minchild = 2;
len --;
for ( ; minchild <= len; minchild *= 2)
{
if (minchild < len && arry[minchild] > arry[minchild+1])
minchild++;
if (arry[minchild] - temp > 0)
{
break;
}
arry[null_node_position] = arry[minchild];
null_node_position = minchild;
}
arry[null_node_position] = temp;
}

template<class T>
T BiHeap<T>::top()
{
assert(len > 0);
return arry[1];
}

template<class T>
void BiHeap<T>::push(T push_value)
{
if (len == size - 1)
{
T *tp = new T[2*size];
memcpy(tp,arry,size*sizeof(T));
size *= 2;
delete []arry;
arry = tp;
}
len ++;
int null_node_position = len;
int FatherNode = len/2;
for ( ; FatherNode >= 1; FatherNode /= 2)
{
if (arry[FatherNode] < push_value)
{
break;
}
arry[null_node_position] = arry[FatherNode];
null_node_position = FatherNode;
}
arry[null_node_position] = push_value;
}

主檔案:

// woniu-heap.cpp : 定義控制檯應用程式的入口點。
#include "stdafx.h"
#include "BiHeap.h"
#include "afxtempl.h"
#include <queue>
#include <iostream>
using namespace std;
#define  TESTNUM 1000

int _tmain(int argc, _TCHAR* argv[])
{
DWORD d_start,d_end;
BiHeap<int> H;
int T = TIME;
int i;
d_start = GetTickCount();
while (T--)
{
for (i=TESTNUM; i>=1; --i)
{
H.push(i);
}
for (i=1; i<=TESTNUM; ++i)
{
H.pop();
}
d_end = GetTickCount();
}
cout<<endl<<"myself time: "<<double(d_end - d_start)<<endl;

T = TIME;
priority_queue<int,vector<int>,greater<int>> stl_H;
d_start = GetTickCount();
while (T--)
{
for (i=TESTNUM; i>=1; --i)
{
stl_H.push(i);
}
for (i=1; i<=TESTNUM; ++i)
{
stl_H.pop();
}
d_end = GetTickCount();
}
cout<<endl<<"stl time: "<<double(d_end - d_start)<<endl;

system("pause");
return 0;
}