I wrote the following C++ code in Visual Studio 2017 to evaluate floating point performance:
#include <iostream>
#include <Windows.h>
int main(void)
{
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1, t2; // ticks
double elapsedTime = 0;
float result = 1000.0f;
float result2 = 2000.0f;
float result3 = 3000.0f;
float result4 = 4000.0f;
float result5 = 5000.0f;
float result6 = 6000.0f;
float result7 = 7000.0f;
float result8 = 8000.0f;
long long i;
// get ticks per second
QueryPerformanceFrequency(&frequency);
// start timer
QueryPerformanceCounter(&t1);
for (i = 0; i < 10000000; i++)
{
result = result + 1.4f;
result2 = result2 + 1.4f;
result3 = result3 + 1.4f;
result4 = result4 + 1.4f;
result5 = result5 + 1.4f;
result6 = result6 + 1.4f;
result7 = result7 + 1.4f;
result8 = result8 + 1.4f;
}
// stop timer
QueryPerformanceCounter(&t2);
// compute the elapsed time in millisec
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
printf("Time for calculation: %f ms\n", elapsedTime);
printf("Resulting value1: %10f\n", result);
printf("Resulting value2: %10f\n", result2);
printf("Resulting value3: %10f\n", result3);
printf("Resulting value4: %10f\n", result4);
printf("Resulting value5: %10f\n", result5);
printf("Resulting value6: %10f\n", result6);
printf("Resulting value7: %10f\n", result7);
printf("Resulting value8: %10f\n", result8);
}
The expected result for variable "result" would therefore be 1400001000, for variable "result2" it would be 1400002000 and so on. However, the result variables all have the value 33554432.000000 at the end of the loop. It doesn't matter if i execute the loop 10 billion times instead of 1 billion times, the results stay the same.
However, when I set the compiler option "floating point model" to "fast", all result variables change to 268435456.000000.
Can anyone of you explain that strange behavior?
I expected correct floating point results.