mercredi 4 août 2021

Multiple instructions in one declaration VS multiple lines and variables

I am tweaking an existing software to make it more efficient. It is using some 3d geometry to compute object properties (trajectories, angles, etc) and is therefore using 3d vectors and scalar products.

Two methods in my 3d geometry dealing class are using the same computation to get an angle between two vectors ; the formula is shown here. The two methods, although they use the same computation, are written in two "different" ways :

vec3d::vec3d(float px, float py, float pz){
    x=px;
    y=py;
    z=pz;
}

float operator*(const vec3d &v1, const vec3d &v2) {
    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}

float vec3d::angle(const vec3d &v2){
    vec3d v1(x, y, z);
    float scalProd = v1 * v2 / std::sqrt((v1 * v1) * (v2 * v2));

    if (scalProd > 1.0) { // rouding errors might happen
        return 0;
    }
    return std::acos(scalProd);
}

float vec3d::cosAngle(const vec3d &v2){
    vec3d v1(x, y, z);
    float scalProd = v1 * v;

    float quotient = (v1 * v1) * (v * v);
    quotient = std::sqrt(quotient);
    scalProd = scalProd / quotient;


    if (scalProd > 1.0) {    // rounding errors
        return 0;
    }
    return (scalProd);
}

My question is on the scalProd declaration/computation: which would be faster/more memory efficient ? And generally speaking, is it good practice to have a long variable declaration with no intermediate variables, or should I favor the readability of the code ?

I also have a subsidiary question: in my float operator*() overloading, would it be worth to use Intel SSE programming, with the use of _mm128 variables ? I already figured out a way to compute a scalar product with this method but it's a bit tedious, I'm wondering if the time gain would really be worth it.

Thanks a lot ! This question might seem a bit basic but I found no other ones comparing execution speed of these two approaches, on SO or anywhere else.

Aucun commentaire:

Enregistrer un commentaire