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;
}