BlueSun
BlueSun

Reputation: 3570

fast double multiplication with integer precision

What is the fastest way to multiply two double numbers with lesser precision (eg Int precision)? Will it be faster when I use:

double a = 2.2;
double b = 3.2;
int c = int(a)*int(b);

or is there a faster way?

edit: Seams like converting to integer precision was a bad idea. I'll try to explain my problem better:

I have a set of double data and i need to extract some properties from it what mainly involves a lot of multiplication. Now I am trying to decrease the calculation time by reducing the calculation precision. Will maybe this:

double a = 2.2;
double b = 3.2;
float c = float(a)*float(b);

work better than integer conversion ?

Upvotes: 0

Views: 1225

Answers (3)

Petr Skocik
Petr Skocik

Reputation: 60068

int(a)*int(b); a 1,000,000,000 times:

real    0m4.946s
user    0m4.852s
sys 0m0.018s

int(a*b); a 1,000,000,000 times:

real    0m4.067s
user    0m3.993s
sys 0m0.010s

float c = float(a)*float(b); a 1,000,000,000 times:
real    0m2.815s
user    0m2.764s
sys 0m0.010s

Each compiled with g++ -O0.

#for_loops

Upvotes: 2

Mark B
Mark B

Reputation: 96241

This looks like a (possibly premature) micro-optimization to me and as such the only way to know for sure is to profile your specific application. So many other factors could affect the performance, such as the time to convert the double to integer etc.

The only thing I can suggest is that if you don't need doubles until later in the process, do all the initial computation as int, and only convert to double at the last possible minute before you need the double precision.

Upvotes: 3

Sly_TheKing
Sly_TheKing

Reputation: 528

 int(a*b);

here you multiply two doubles, because conversion is done after multiplying (also you convert to int then to double, so you make it more inefficient, plus not accurate)

therefore, the solution is second snippet, because u convert before multiplication

 int(a)*int(b)

Upvotes: 1

Related Questions