In reference to the thread on
delete[]
and this old thread:
Vector vs. array.
I have updated the code to use dynamic memory allocation for the array model.
Here is the code I used (generally unmodified from previous test, aside from adding extra code to do the dynamic memory allocation):
Key:Code:#include <iostream> #include <iomanip> #include <vector> #include <ctime> const int size = 128; class B { public: virtual int sum() = 0; virtual ~B() {} }; class V : public B { private: std::vector < std::vector <int> > vec; public: V() { for(int i = 0; i < size; i++) { vec.push_back(std::vector<int>(0)); for(int j = 0; j < size; j++) { vec[i].push_back(i * j); } } } virtual int sum() { int s = 0; for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) s += vec[i][j]; return s; } }; class A : public B { private: int arr[size][size]; public: A() { for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { arr[i][j] = i * j; } } } int sum() { int s = 0; for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) s += arr[i][j]; return s; } }; class D: public B { private: int **parr; public: D() { parr = new int*[size]; for(int i = 0; i < size; i++) { parr[i] = new int[size]; for(int j = 0; j < size; j++) { parr[i][j] = i * j; } } } ~D() { for(int i = 0; i < size; i++) { delete [] parr[i]; } delete [] parr; } int sum() { int s = 0; for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) s += parr[i][j]; return s; } }; int func(B *b) { return b->sum(); } void timeIt(char *name, int (*f)(B *b), B * b) { int x = 0; clock_t t = clock(); for(int i = 0; i < 1000000; i++) { x += f(b); } t = clock() - t; std::cout << "x = " << x << std::endl; std::cout << name << ": " << std::setprecision(6) << static_cast<double>(t) / CLOCKS_PER_SEC << std::endl; } #define TIME_IT(f, b) do { timeIt(#b, f, &b); } while(0) int main() { A a; V v; D d; TIME_IT(func, a); TIME_IT(func, v); TIME_IT(func, d); }
a - fixed size array on the stack.
v - vector of vector.
d - dynamically allocated 2D array.
Result: g++ -O2 -fomit-frame-pointer -funroll-loops
Result: Visual Studio .Net (VC++ version 7.0, cl version 13.00)Code:x = -802947072 a: 12.031 x = -802947072 v: 11.297 x = -802947072 d: 12.907
As you can see (and as I expected), the dynamic variant ends up closer to vector, but still slightly slower than the fixed size array.Code:x = -802947072 a: 6.218 x = -802947072 v: 10.75 x = -802947072 d: 7.891
--
Mats



LinkBack URL
About LinkBacks



CornedBee