vector,数组,动态数组效率测试

对vector、数组、new创建的动态数组、预先reverse的vector测试代码如下:

#include 
#include 
#include 
#include 

#define QueryFreAndCounter(m_fre,tt) QueryPerformanceFrequency(&m_fre);\
	QueryPerformanceCounter(&tt);
#define  Timecost(t2,t1,fre,tt1)\
	QueryPerformanceCounter(&t2);\
	tt1=(double)1000.0*(t2.QuadPart - t1.QuadPart) / fre.QuadPart;

using namespace std;
using namespace cv;
void main()
{
	//vector,数组,动态数组效率测试
	int t = 100,t1=100,t2=100,t3=100;
	int n = 200000;
	double TimeCost = 0;
	LARGE_INTEGER m_frequency = { 0 }, m_time1 = { 0 }, m_time2 = { 0 };
	QueryFreAndCounter(m_frequency, m_time1);
	while (t)
	{
		int a[200000];
		for (int i = 0; i < n;++i)
		{
			a[i] = i;
		}
		--t;
	}
	Timecost(m_time2, m_time1, m_frequency, TimeCost);
	printf("array cost %.3f ms!\n", TimeCost);

	QueryFreAndCounter(m_frequency, m_time1);
	while (t1)
	{
		vector<int> a;
		a.resize(n + 1);
		for (int i = 0; i < n; ++i)
		{
			a.push_back(i);
		}
		--t1;
	}
	Timecost(m_time2, m_time1, m_frequency, TimeCost);
	printf("reverse_vector cost %.3f ms!\n", TimeCost);

	QueryFreAndCounter(m_frequency, m_time1);
	while (t2)
	{
		int *a=new int[n+1];
		for (int i = 0; i < n; ++i)
		{
			a[i] = i;
		}
		delete[]a;
		--t2;
	}
	Timecost(m_time2, m_time1, m_frequency, TimeCost);
	printf("dynamic array cost %.3f ms!\n", TimeCost);

	QueryFreAndCounter(m_frequency, m_time1);
	while (t3)
	{
		vector<int> a;
		for (int i = 0; i < n; ++i)
		{
			a.push_back(i);
		}
		--t3;
	}
	Timecost(m_time2, m_time1, m_frequency, TimeCost);
	printf("vector cost %.3f ms!\n", TimeCost);
	cvWaitKey(0);
}

debug下结果
vector,数组,动态数组效率测试_第1张图片
release下结果
vector,数组,动态数组效率测试_第2张图片
总结,效率:数组>new创建的动态数组>vector>预先reverse的vector。理论上预先reverse的vector效率应该比vector高(参考链接中是这样),但是结果并没有,如果问题,欢迎讨论~
参考链接

你可能感兴趣的:(C++,C)