vector在数据量大时的修改

结果函数result_0要比运算次数大它1000倍的时间还长
在vector使用时,都需要调用自身内部函数,无论你定义是:vector<int> *p = new vector<int>,还是vector<int> p;元素都是在堆上进行分配的
在栈的操作远比在堆的操作快上很多
所以在大数据时,尽量减少vector使用,可以直接使用指针的方式来代替对vector操作
 数据增加,可以通过指针地址偏移来加快对数据的读取,其速度比使用对vector操作,时间量级上相差很大

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <windows.h>
using namespace std;

int result_0(int i )
{
	vector<int> sum;
	sum.push_back(0);
	if(0 == i )
	{
		return (1);
	}
	else
	{
		sum[0] = i + result_0(i-1);
	}

	return sum[0];
}

int result_1(int i)
{
	int sum;
	if(0 == i )
	{
		return (1);
	}
	else
	{
		sum = i + result_1(i-1);
	}
	return sum;	
}

int _tmain(int argc, _TCHAR* argv[])
{
	DWORD64 nLoopCount = 100000;
	int	nLoop;
	DWORD64 nResult = 0;

	DWORD start,end;

	///
	nResult = 0;
	start = ::GetTickCount();
	for(nLoop = 0; nLoop < nLoopCount; nLoop ++){
		nResult += result_0(100);
	}
	end = ::GetTickCount();
	cout << "result_0 takes: " << end - start << " ms, result = " << nResult << std::endl;
	///
	nLoopCount *= 1000;
	nResult = 0;
	start = ::GetTickCount();
	for(nLoop = 0; nLoop < nLoopCount; nLoop ++){
		nResult += result_1(100);
	}
	end = ::GetTickCount();
	cout << "result_1 takes: " << end - start << " ms, result = " << nResult << std::endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值