473,748 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Operator overloading, C++ performance crappiness

Is there any way to get to the left-hand side of an operator? Consider
the following (this is not meant to be perfect code, just an example of
the problem):

class Matrix
{
public:
int data[1024];

Matrix() {}

Matrix(int value)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
data[i] = value;
}

void add(const Matrix& obj, Matrix* output)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
output->data[i] = data[i] + obj.data[i];
}

Matrix operator +(const Matrix& obj)
{
Matrix temp; // "unnecessar y" creation of temp variable

for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
temp.data[i] = data[i] + obj.data[i];

return temp; // "unnecessar y" extra copy of output
}
};

For nice looking syntax you _really_ want to use the operator+ like:
matrix3 = matrix1 + matrix2;

However, that is some 50% slower than the _much_ uglier:
matrix1.add(mat rix2, &matrix3);

If only there were a way to get to the left-hand argument of the
operator+ then it could be fast and easy to use. Consider the following
code which is not valid C++ and will not compile for this example:

Matrix as M
operator+(const Matrix& obj)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
M.data[i] = data[i] + obj.data[i];
}

That would be fast and clean to use. Is there any way to accomplish
this? Otherwise the situation is just ugly and there is no point in
using operator overloading for these types of situations (which really
defeats the purpose of operator overloading in the first place).

Thanks! Jo
Aug 17 '05
51 3589
Kai-Uwe Bux wrote:

Karl Heinz Buchegger wrote:
[snip]
int main()
{
Matrix a(2), b(3), c;
time_t start, end;

start = clock();
for( int j = 0; j < 100000; ++j )
c = a + b;
end = clock();


Are you sure the compiler did not optimize away all of the loop?
After all, neither a nor b nor c are changing.#


Thats what I initially thought also.
But then I tried an experiment: I increased the number
of iterations and with that the time increased. For me
this is evicence enough that the loop is not
optimized away entirely.
--
Karl Heinz Buchegger
kb******@gascad .at
Aug 18 '05 #41
Jojo wrote:

Karl Heinz Buchegger wrote:
The free standing version usually is the prefered one for operator+, operator+,
operator*, ... (all operators that return a temporary object and not a reference
to *this).

Even if I change the free standing function back into a member function,
the operator+ version is still faster (by roughly the same amount) then
the add() version.

So either your measurement code is incorrect or you did not turn on
the optimizer for your measurements, since I can't believe that VC++ 6.0
outperforms gcc in terms of code optimization.
Thanks. I don't think there is any difference in speed between the
add() method and the overloaded operator though. I think the difference
you are seeing is from already having the output loaded on the second
run.


Then the second run should actually be faster, don't you think.
But in reality quite the contrary is true. The second run through
the loop, using the add() function is slower.
The CPU will optimize away some of the value changes because they
are exactly the same on the second run. If you separate out the two
versions and run two separate instances the timing will be exactly the same.


Just switch the 2 code parts and see if the results are the same.
Hint: They are the same.

--
Karl Heinz Buchegger
kb******@gascad .at
Aug 18 '05 #42
Jojo wrote:
Is there any way to get to the left-hand side of an operator? Consider
the following (this is not meant to be perfect code, just an example of
the problem):

class Matrix
{
public:
int data[1024];

Matrix() {}

Matrix(int value)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
data[i] = value;
}

void add(const Matrix& obj, Matrix* output)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
output->data[i] = data[i] + obj.data[i];
}

Matrix operator +(const Matrix& obj)
{
Matrix temp; // "unnecessar y" creation of temp variable

for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
temp.data[i] = data[i] + obj.data[i];

return temp; // "unnecessar y" extra copy of output
}
};

For nice looking syntax you _really_ want to use the operator+ like:
matrix3 = matrix1 + matrix2;

However, that is some 50% slower than the _much_ uglier:
matrix1.add(mat rix2, &matrix3);

If only there were a way to get to the left-hand argument of the
operator+ then it could be fast and easy to use. Consider the following
code which is not valid C++ and will not compile for this example:

Matrix as M
operator+(const Matrix& obj)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
M.data[i] = data[i] + obj.data[i];
}

That would be fast and clean to use. Is there any way to accomplish
this? Otherwise the situation is just ugly and there is no point in
using operator overloading for these types of situations (which really
defeats the purpose of operator overloading in the first place).


I guess somebody else already mentioned expression templates. Here is some
code for experimentation :

unsigned long const rank = 1024;
unsigned long const runs = 12345;

template < typename VectorExprA,
typename VectorExprB >
struct VectorSum {

typedef typename VectorExprA::va lue_type value_type;

VectorExprA const & a;
VectorExprB const & b;

VectorSum( VectorExprA const & a_,
VectorExprB const & b_ )
: a ( a_ )
, b ( b_ )
{}

value_type operator[] ( unsigned long i ) const {
return( a[i] + b[i] );
}

}; // struct VectorSum<>;

template < typename arithmetic_type ,
unsigned long dim >
class Vector {
public:

typedef arithmetic_type value_type;

private:

value_type entry [dim];

public:

Vector ( value_type val = value_type() ) {
for ( unsigned long i = 0; i < dim; ++i ) {
entry[i] = val;
}
}

Vector & operator= ( Vector const & other ) {
for ( unsigned int i = 0; i < dim; ++i ) {
this->entry[i] = other.entry[i];
}
return( *this );
}

template < typename VectorExpr >
Vector & operator= ( VectorExpr const & expr ) {
for ( unsigned long i = 0; i < dim; ++i ) {
this->entry[i] = expr[i];
}
return( *this );
}

value_type const & operator[] ( unsigned long i ) const {
return( entry[i] );
}

value_type & operator[] ( unsigned long i ) {
return( entry[i] );
}

void add ( Vector const & other, Vector & result ) const {
for( unsigned int i = 0; i < dim; ++i ) {
result.entry[i] = this->entry[i] + other.entry[i];
}
}

}; // class Vector<>;

template < typename VectorExprA,
typename VectorExprB >
inline
VectorSum< VectorExprA, VectorExprB > operator+ ( VectorExprA const & a,
VectorExprB const & b ) {
return( VectorSum< VectorExprA, VectorExprB >( a, b ) );
}


#include <iostream>
#include <ctime>
#include <cstdlib>

void test_operator1 ( void ) {
Vector< double, rank > a ( 0 );
Vector< double, rank > b ( 1 );
std::clock_t ticks = std::clock();
{
for ( unsigned int i = 0; i < runs; ++i ) {
a = a + b;
}
}
ticks = std::clock() - ticks;
std::cout << "opp1: a[0] = " << a[0] << " time: " << ticks << '\n';
}

void test_operator2 ( void ) {
Vector< double, rank > a ( 0 );
Vector< double, rank > b ( 1 );
std::clock_t ticks = std::clock();
{
for ( unsigned int i = 0; i < runs; ++i ) {
a = a + b + b;
}
}
ticks = std::clock() - ticks;
std::cout << "opp2: a[0] = " << a[0] << " time: " << ticks << '\n';
}
void test_add1 ( void ) {
Vector< double, rank > a ( 0 );
Vector< double, rank > b ( 1 );
std::clock_t ticks = std::clock();
{
for ( unsigned int i = 0; i < runs; ++i ) {
a.add( b, a );
}
}
ticks = std::clock() - ticks;
std::cout << "add1: a[0] = " << a[0] << " time: " << ticks << '\n';
}

void test_add2 ( void ) {
Vector< double, rank > a ( 0 );
Vector< double, rank > b ( 1 );
std::clock_t ticks = std::clock();
{
for ( unsigned int i = 0; i < runs; ++i ) {
a.add( b, a );
a.add( b, a );
}
}
ticks = std::clock() - ticks;
std::cout << "add2: a[0] = " << a[0] << " time: " << ticks << '\n';
}

int main ( void ) {
std::srand( 24163 );
while ( true ) {
switch ( std::rand() % 4 ) {
case 0 :
test_operator1( );
break;
case 1 :
test_operator2( );
break;
case 2 :
test_add1();
break;
case 3 :
test_add2();
break;
}
}
}
On my machine (OS: Linux; CPU: intel; CC: g++-4.0.1 all optimization turned
on), opp1 and add1 are essentially equivalent and opp2 beats add2.
Best

Kai-Uwe Bux

Aug 18 '05 #43

Victor Bazarov wrote:
Jojo wrote:
6703 is for add() method
11484 is for "c = a + b"


Yes, I believe that. I've tested on several compilers/systems and all
pretty much give the same result, 'add' is two-three times better. The
difference undoubtedly comes from the fact that the matrix needs to be
copied to and fro.


can you compare result with

#include <iostream>

using namespace std;

const int dim=4;

struct matrix {
int * data;
int size;

explicit matrix () : data (new int[dim]), size (dim) { }

explicit matrix (int value) : data (new int[dim]), size (dim) {
for ( int i=0; i<size; ++i ) data[i]=value;
}

~matrix () { delete [] data; }

matrix (const matrix &);

matrix & operator = (const matrix & x) {
matrix * ptr=const_cast< matrix *>(&x);
delete [] this->data;
this->data=ptr->data;
this->size=ptr->size;
ptr->data=0; ptr->size=0;
return (*this);
}

int & operator [] (int i) { return data[i]; }
const int & operator [] (int i) const { return data[i]; }

};
matrix operator + ( const matrix & x, const matrix & y ) {
matrix temp;

for (int i=0; i<temp.size; ++i) temp[i]=x[i]+y[i];

return temp;
}

int main () {

matrix a(2);
matrix b(3);
matrix c;

c=a+b;

return 0;
}

Aug 18 '05 #44

Jojo wrote:
<snip>

If you really want to add performance you might find pointer arithmetic
is faster than using array access. Thus:

class Matrix
{
public:
enum { numElements = 1024 };

int data[numElements];
Matrix() {}
explicit Matrix(int value)
{
int* begin( data );
int* end( data + numElements );
while ( begin != end )
{
*begin = value;
++begin;
}
}

Matrix& operator+=( const Matrix& rhs )
{
int* begin( data );
int* end( data + numElements );
const int* srcBegin( rhs.data );
while ( begin != end )
{
*begin = *srcBegin;
++begin;
++srcBegin;
}
return *this;
}
}

Matrix operator+( const Matrix& lhs, const Matrix& rhs )
{
Matrix temp( lhs );
return temp += rhs;
}
If you want to do operator+ without copy-construction then

Matrix operator+( const Matrix& lhs, const Matrix& rhs )
{
Matrix temp;
int* destBegin ( temp.data );
const int* src1Begin( lhs.data );
const int* src2Begin( rhs.data );
int* destEnd( destBegin + Matrix::numElem ents );
while ( destBegin != destEnd )
{
*destBegin = *src1Begin + *src2Begin;
++destBegin;
++src1Begin;
++src2Begin;
}
};

Note, you could also use post-increment on the pointers which appears
to use fewer lines of code but in reality would probably generate the
same assembly code here (with regular pointers) could could generate
more code (using iterators).

(And you can change the use of the word Begin to something like Pos if
you think Begin is a misnomer).

Note: you'll probably find that STL implements its algorithms similar
to how I just did, and you might want to actually use them.

Aug 18 '05 #45
Aleksey Loginov wrote:
Victor Bazarov wrote:
Jojo wrote:
6703 is for add() method
11484 is for "c = a + b"


Yes, I believe that. I've tested on several compilers/systems and all
pretty much give the same result, 'add' is two-three times better. The
difference undoubtedly comes from the fact that the matrix needs to be
copied to and fro.

can you compare result with

[...]


I just went ahead and merged the OP's 'Matrix' code with your 'matrix',
and then ran 5 million loops of additions for one and then for the other.
The results are interesting, implementing crude "move" semantics does
give an advantage:

2 3 5 21804
2 3 5 13142

(the first is for the 'Matrix' additions, the latter is for 'matrix').

I had to adjust your 'dim' to 1024 to match the original code. I did
implement the copy constructor (although some compilers didn't seem to
need it), just in case.

V
Aug 18 '05 #46

Victor Bazarov wrote:
Aleksey Loginov wrote:
Victor Bazarov wrote:
Jojo wrote:

6703 is for add() method
11484 is for "c = a + b"

Yes, I believe that. I've tested on several compilers/systems and all
pretty much give the same result, 'add' is two-three times better. The
difference undoubtedly comes from the fact that the matrix needs to be
copied to and fro.

can you compare result with

[...]


I just went ahead and merged the OP's 'Matrix' code with your 'matrix',
and then ran 5 million loops of additions for one and then for the other.
The results are interesting, implementing crude "move" semantics does
give an advantage:

2 3 5 21804
2 3 5 13142

(the first is for the 'Matrix' additions, the latter is for 'matrix').


what time for add() method?

I had to adjust your 'dim' to 1024 to match the original code. I did
implement the copy constructor (although some compilers didn't seem to
need it), just in case.


thanks.
can you try this code, please?

#include <iostream>

using namespace std;

const int dim=1024;

struct matrix {
int * data;
int size;

struct matrix_ref {
matrix * ptr;
matrix_ref ( matrix * x ) : ptr (x) { }
matrix * operator -> () { return ptr; }
};

explicit matrix () : data (new int[dim]), size (dim) { }

explicit matrix (int value) : data (new int[dim]), size (dim) {
for ( int i=0; i<size; ++i ) data[i]=value;
}

explicit matrix (const matrix &);

~matrix () { delete [] data; }
matrix (matrix_ref ptr) : data(0), size(0) {
this->reset (ptr);
}

matrix & operator = (matrix & x) {
this->reset (x);
return (*this);
}

matrix & operator = (matrix_ref ptr) {
this->reset (ptr);
return (*this);
}

operator matrix_ref () { return matrix_ref (this); }
void reset ( matrix_ref ptr ) {
delete [] this->data;
this->data=ptr->data;
this->size=ptr->size;
ptr->data=0; ptr->size=0;
}

int & operator [] (int i) { return data[i]; }
const int & operator [] (int i) const { return data[i]; }

};
matrix operator + ( const matrix & x, const matrix & y ) {
matrix temp;

for (int i=0; i<temp.size; ++i) temp[i]=x[i]+y[i];

return temp;
}

int main () {

matrix a(2);
matrix b(3);
matrix c;

c=a+b;

return 0;
}

Aug 18 '05 #47
Aleksey Loginov wrote:
Victor Bazarov wrote:
Aleksey Loginov wrote:
Victor Bazarov wrote:
Jojo wrote:
>6703 is for add() method
>11484 is for "c = a + b"

Yes, I believe that. I've tested on several compilers/systems and all
pretty much give the same result, 'add' is two-three times better. The
differenc e undoubtedly comes from the fact that the matrix needs to be
copied to and fro.
can you compare result with

[...]


I just went ahead and merged the OP's 'Matrix' code with your 'matrix',
and then ran 5 million loops of additions for one and then for the other.
The results are interesting, implementing crude "move" semantics does
give an advantage:

2 3 5 21804
2 3 5 13142

(the first is for the 'Matrix' additions, the latter is for 'matrix').

what time for add() method?


Your class 'matrix' doesn't have 'add' method.
I had to adjust your 'dim' to 1024 to match the original code. I did
implement the copy constructor (although some compilers didn't seem to
need it), just in case.

thanks.
can you try this code, please?

[..]


Sorry, I don't have time at this point. Maybe over the weekend if you are
still interested by then.

V
Aug 18 '05 #48

Victor Bazarov wrote:
Aleksey Loginov wrote:
Victor Bazarov wrote:
Aleksey Loginov wrote:

Victor Bazarov wrote:
>Jojo wrote:
>
>
>>6703 is for add() method
>>11484 is for "c = a + b"
here

>Yes, I believe that. I've tested on several compilers/systems and all
>pretty much give the same result, 'add' is two-three times better. The
>differenc e undoubtedly comes from the fact that the matrix needs to be
>copied to and fro.
can you compare result with

[...]

I just went ahead and merged the OP's 'Matrix' code with your 'matrix',
and then ran 5 million loops of additions for one and then for the other.
The results are interesting, implementing crude "move" semantics does
give an advantage:

2 3 5 21804
2 3 5 13142

(the first is for the 'Matrix' additions, the latter is for 'matrix').

what time for add() method?


Your class 'matrix' doesn't have 'add' method.


i thought OP have... no matter.
I had to adjust your 'dim' to 1024 to match the original code. I did
implement the copy constructor (although some compilers didn't seem to
need it), just in case.

thanks.
can you try this code, please?

[..]


Sorry, I don't have time at this point. Maybe over the weekend if you are
still interested by then.


i can wait, it's not a problem.

i work with gcc 3.2, so can't get real results by myself...

Aug 19 '05 #49
Aleksey Loginov wrote:
[...]
i work with gcc 3.2, so can't get real results by myself...


Hmm... I didn't know gcc 3.2 was unable to produce real results...
Aug 19 '05 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2858
by: Steve Sargent | last post by:
Hi: I'm trying to debug the following code, and it keeps looping on the if statement: public static bool operator == (OnlineMemberNode first, OnlineMemberNode second) { if(first == null) {
17
2509
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: public static bool operator !=(MyType x, MyType y) { return !(x == y); } That way the == operator handles everything, and extra comparing logic isn't
0
8983
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8822
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9359
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9310
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9236
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3298
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.