Exception Handling - Performance Drag?

Hey all. This is spooking me out. Can anyone explain this...

I have a matrix class, I'm currently testing the performance of the solve function (solves for x in Ax = b). The most called function is my Matrix element access operator: (). Here is its implementation:

1
2
3
4
5
6
7
8
9
template <class T>
T& Matrix<T>::operator()(unsigned int row, unsigned int col) const throw(Exception){

    if(row >= numRows || row < 0 || col >= numCols || col < 0){
        throw Exception(INDEX_OUT_OF_BOUNDS,"Error in Matrix () operator: Matrix index out of bounds.");
    }
    return this->matArray[row*(numCols) + (col)];

}


Now current run time is 2 seconds. There are no exceptions thrown. If I comment out the throw line then run time drops to .5 seconds. How can such a drop occur when the exception was never being thrown?

Also this performance drag exception handling appears to cause is a worry. Should I just go back to returning integer values.

I can't get gprof to work on windows XP - the debugging symbols don't show. I'm using codeblocks. Does anyone know a good code profiler that is easy to use on WinXP with codeblocks?

And lastly, if I have a = b*c*d, that will be calculated as a = b*(c*d) right?

Thanks.

Nick.
Last edited on
Now current run time in 2 seconds. There are no exceptions thrown! If I comment out the throw line then run time drops to .5 seconds. How can such a drop occur when the exception was never being thrown?


If you comment out the throw line, the if block becomes empty and the compiler can optimize it, and the 4-part bound check, out of the program.

In other words it's not the exception that's slowing you down, it's probably the bounds checking.

Try doing this and see how it compares:

1
2
3
4
if(0)
{
  throw ....
}


If my hunch is right, this will run as fast as when you have the exception commented out.


Also this performance drag exception handling appears to cause is a worry. Should I just go back to returning integer values.


This is why classes like vector don't do bounds checking in their [] operator. The performance hit would be too severe in some situations.

If you're concerned with this class's performance, you might want to consider removing the bounds checking entirely.

And lastly, if I have a = b*c*d, that will be calculated as a = b*(c*d) right?


No. Operators are executed left to right in order of precedence. So it would be a = (b*c)*d.

But really it shouldn't matter. If you need it happen in a specific order I would use parenthesis even if they technically aren't necessary.
Last edited on
Haha dead on Disch. Thanks again! You've helped me numerous times on this forum!
Topic archived. No new replies allowed.