Is it possible to multiply float / double by 0.5 instead of dividing by 2 in C # and C ++?

Mostly for things like this (not real code):

for(int i = 0; i < 1000000000; ++i)
{
     Vert v0 = mesh.polygons[i].edges[0].vert0;
     Vert v1 = mesh.polygons[i].edges[0].vert1;

     Vector3 center = (v0.pos + v1.pos) / 2;
}

v0.poshas a type Vector3<float, float, float>, but maybe Vector3<double, double, double>.

Can you just do it ?:

Vector3 center = (v0.pos + v1.pos) * 0.5;

This may seem like premature optimization, but it should be as fast as possible, which will be called billions of points (point clouds).

+5
source share
1 answer

Not an expert in C ++ in any way, but in C # by doing this:

var a = new Func<float, float, double>((float f1, float f2) => (f1 + f2) * 0.5);
var b = new Func<float, float, double>((float f1, float f2) => (f1 + f2) / 2);

generates IL, which in the first:

  • Loads Arguments
  • Adds them (creates one)
  • Converts the result to double
  • Loads a double argument (0.5)
  • Multiplies (creates double)
  • Returns result

and the last

  • Loads Arguments
  • Adds them (creates one)
  • Loads a constant integer (2)
  • Divides ( , single/integer )

, , , , 2 , , , ( ).

:

Console.Out.WriteLine(((double)1) * ((double)1/3));
Console.Out.WriteLine((1) / ((float)3));

:

0.333333333333333
0.3333333

, "", , , .

+3

All Articles