结果函数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;
}