How can I optimize vector normalization in a Molecular Modeling program?

wetboy wetboy at
Mon Nov 8 16:15:34 EST 1999

In comp.lang.c willkn at wrote:
: Hi, I've been working on a molecular modeling program and have been
: trying to improve its performance recently.  I did some profiling and
: found that the most time by far (41.4%) was spent in a function which
: normalizes a 3-dimensional vector (profiling statistics are given at
: the bottom).

: I am wondering if anyone has suggestions for optimizing that operation.
: Thanks,
: William Knight
: willkn at

: The definition of the function is given below:

: typedef double VTYPE;
: typedef VTYPE Vector[3];

: ////////////////////////////////////////////////////////////////////////
: ////////
: // MakeUnitVector
: //
: // Reduces a normal vector specified as a set of three coordinates,
: // to a unit normal vector of length one.
: //
: bool MakeUnitVector(Vector v)
: 	{
: 	VTYPE length;

: 	// Calculate the length of the vector
: 	length = (VTYPE)sqrt((v[0]*v[0]) + (v[1]*v[1]) + (v[2]*v[2]));

: 	// if length is zero, bail
: 	if(length == 0)
: 		return false;

: 	// Divide each element by the length to get a unit vector.
: 	v[0] /= length;
: 	v[1] /= length;
: 	v[2] /= length;

: 	return true;
: 	}// MakeUnitVector

A few quick thoughts:

  1. Consider whether you really need double precision.  You
     might try two runs of your computation, one with double
     precision, the other with single precision, and compare
     the results.

  2. Square roots take a lot of time.  Can you work with
     the squared values, and avoid taking square roots?

  3. Consider the big picture:  Why are you doing this
     step?  Can you eliminate it, or integrate it better
     with what you're trying to do overall, so as to make
     the whole thing simpler and faster?

  4. If you're stuck with doing the square roots, you might
     surf the internet for faster algorithms.

-- Wetboy

More information about the Molmodel mailing list