Re: Vector vs. Array
Hi,
I think ?? Tiib is right. The code does not return anything. Therefore
the array version seems to be faster than the vector version.
This is the entire code:
#define _SECURE_SCL 0
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<float> v1;
float v2[128];
int iterations =1000000;
for (int i = 0; i < 128; i++)
{
v1.push_back(i);
v2[i] = i;
}
clock_t start = clock();
for (int i = 0; i < iterations; i++)
{
float sum = 0;
for (int i = 0; i < 128; i++)
{
sum += fabs((v2[i])-v2[i]);
}
}
clock_t end = clock();
std::cout << "Testing time (array): " << float(end - start) /
CLOCKS_PER_SEC << " seconds" << std::endl;
start = clock();
for (int i = 0; i < iterations; i++)
{
float sum = 0;
for (int i = 0; i < 128; i++)
{
sum += fabs(v1[i]-v1[i]);
}
}
end = clock();
std::cout << "Testing time (vector): " << float(end - start) /
CLOCKS_PER_SEC << " seconds" << std::endl;
getchar();
return 0;
}
Independent of the number of iterations, the array version returns
always 0 seconds and the vector version multiple seconds up to minutes
(in release mode).
If I add some output code like this:
#define _SECURE_SCL 0
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<float> v1;
float v2[128];
int iterations =1000000;
for (int i = 0; i < 128; i++)
{
v1.push_back(i);
v2[i] = i;
}
int a = 0;
clock_t start = clock();
for (int i = 0; i < iterations; i++)
{
float sum = 0;
for (int i = 0; i < 128; i++)
{
sum += fabs((v2[i])-v2[i]);
}
a += sum;
}
std::cout << a << std::endl;
clock_t end = clock();
std::cout << "Testing time (array): " << float(end - start) /
CLOCKS_PER_SEC << " seconds" << std::endl;
a = 0;
start = clock();
for (int i = 0; i < iterations; i++)
{
float sum = 0;
for (int i = 0; i < 128; i++)
{
sum += fabs(v1[i]-v1[i]);
}
a+=sum;
}
std::cout << a << std::endl;
end = clock();
std::cout << "Testing time (vector): " << float(end - start) /
CLOCKS_PER_SEC << " seconds" << std::endl;
getchar();
return 0;
}
Then both code versions need approx. the same time (0.6s).
Regards,
Peter
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]