Re: help with vector<vector<double>>
T. Crane <trevis.crane@gmail.com> wrote in message...
On Aug 10, 2:47 pm, "Bo Persson" <b...@gmb.dk> wrote:
If you don't know, and the numbers are reasonably random, you will get
a good performance *on average*. Note that after "shooting yourself in
the foot" at 101, you get the next 99 push_backs for free. If you
reallocate at a-million-and-one, you get the next million or so
push_backs for free. That's cheap!
Bo Persson
So I was curious to see which is faster -- pushing back onto a vector
or using direct index access of the elements. I declare a
std::vector<int> v, setting the number of elements to vSize. I set
the values using a for-loop. Then, I declare two
std::vector<vector<int> > objects, m1 & m2. The first of these I
initialize with mSize elements, and the second I use the
std::vector::reserve method to claim mSize space. The using two for-
loops I populate m1 & m2 using direct index accessing of the elements
to set them equal to v, and then I use push_back to fill m2. I time
these two for-loops as well as the whole function. What I find
(perhaps not suprisingly) is that I fill m1 much, much faster, i.e.
push_back() with reserve() are SLOW. Anyway, here's the code.
Nothing to special.
#include <vector>
#include <iostream>
#include <iomanip>
#include <time.h>
using namespace std;
int main(){
time_t t0_0,t1_0,t2_0;
time_t t0_f,t1_f,t2_f;
t0_0 = time(NULL);
int vSize = 10000000;
int mSize = 10;
vector<int> v(vSize);
for (int i=0;i<vSize;i++){v.at(i) = i;}
vector<vector<int> > m1(mSize);
vector<vector<int> > m2;
m2.reserve(mSize);
t1_0 = time (NULL);
for (int j=0;j<mSize;j++){m1.at(j) = v;}
t1_f = time(NULL);
t2_0 = time(NULL);
for (int i=0; i<mSize;i++){ m2.push_back(v);}
t2_f = time(NULL);
t0_f = time(NULL);
cout << "testTime0 = " << t0_f-t0_0 << endl;
cout << "testTime1 = " << t1_f-t1_0 << endl;
cout << "testTime2 = " << t2_f-t2_0 << endl;
return 0;
}
[ my opinion ]
And your results may be false. Put the vector operations in functions, and
'call' them at least 1000 times, capturing the elapsed time each pass.
Examine the mean and deviations of the times.
If you are running on an OS, the OS can intefere with the times you got.
(memory management, other programs running (background), etc.)
I've run some time tests on vectors that iterated 100 times[1], and the
result fluctuated between 50 to 150 ticks ( std::clock_t() ) on multiple
runs.
V1 might take 50 ticks and V2 150 ticks on one run, and the times reverse on
the next run.
[1] - construct, fill, destruct cycle.
--
Bob R
POVrookie