I was wondering if the length of a double variable causes an impact on the multiplication time. For testing purposes, I wrote the folowing small piece of code:
#include <iostream>
#include <time.h>
int main() {
double x = 123.456;
double a = 1.23456;
double b = 1.234;
double d = 1.0;
// experiment 1
clock_t start = clock();
for( unsigned long long int i = 0; i < 10000000; ++i ) {
x *= a;
}
clock_t end = clock();
std::cout << "123.456*1.23456 takes " << (double)(end-start)/CLOCKS_PER_SEC << " secs" << std::endl;
// experiment 2
start = clock();
for( unsigned long long int i = 0; i < 10000000; ++i ) {
x *= b;
}
end = clock();
std::cout << "123.456*1.234 takes " << (double)(end-start)/CLOCKS_PER_SEC << " secs" << std::endl;
// experiment 3
start = clock();
for( unsigned long long int i = 0; i < 10000000; ++i ) {
x *= d;
}
end = clock();
std::cout << "123.456*1.0 takes " << (double)(end-start)/CLOCKS_PER_SEC << " secs" << std::endl;
return 0;
}
I compiled it using VS2008, 64bit in release mode, without optimization and debug information. The result was not surprising: all three kinds of multiplication last exactly the same time, with difference in just a few milliseconds. My question is: why is that so? If I make a mistake and multiply a number by 1.0 instead of 1, and I do not use any compiler optimization, then my multiplication will last much longer than multiplying a number by 1! When humans multiply, then the shorter the number, the faster we come to the result. How does computer multiply so that it does not matter, how long the two numbers are?
Apart from that, I decided to check whether debugging influences runtime speed. In this case, it does not: compiling with \DEBUG
option or without, multiplication always takes exactly the same amount of time.
With optimization enabled \O2
, the same multiplication lasts only a thousandth of a second. What does optimization do in this case? How can such a compact code of multiplying two doubles in C++ be optimized?
I would be grateful for any explanation, what happens during double multiplication in C++.