Tuesday, November 24, 2009

Templates v subclasses v.2

A slightly more complicated test similar to the previous post. In this case the templated version doesn't have such a huge advantage.

Subclassed version:

#include <iostream>

using namespace std;

class mybaseclass {
public:

virtual int get_i() = 0;
};

class myclass : public mybaseclass {

public:

myclass(int in) {
i=in;
}

int get_i() {
i++;
return i;
}

int i;
};

class otherclass : public mybaseclass {

public:

otherclass(int in) {
i = in;
}

int get_i() {
return i*i;
}

int i;
};

int main(void) {
myclass *c = new myclass(2);

double sum=0;
for(size_t n=0;n<2000000000;n++) {

mybaseclass *cc = c;

sum += (static_cast<double>(cc->get_i())/2.2);

}
cout << sum << endl;
delete c;
}


Templated version:
#include <iostream>

using namespace std;

template<class t>
class myclass {

public:

myclass(int in) {
i=in;
}

inline int get_i() {
i++;
return i;
}

int i;
};

template<class t>
class otherclass {

public:

otherclass(int in) {
i = in;
}

inline int get_i() {
return i*i;
}

int i;
};

int main(void) {
myclass<int> *c = new myclass<int>(2);

double sum=0;
for(size_t n=0;n<2000000000;n++) {

sum += (static_cast<double>(c->get_i())/2.2);

}
cout << sum << endl;
delete c;
}



$ g++ small_classed.cpp -O3;time ./a.out
9.09091e+17

real 0m21.151s
user 0m20.909s
sys 0m0.072s


$ g++ small_templateclassed.cpp -O3;time ./a.out
9.09091e+17

real 0m20.736s
user 0m20.527s
sys 0m0.064s

No comments: