Integer variables with variables versus binary

For some reason, my code is capable of performing swaps twice as fast as integers. I have no idea why this is happening.

On my machine, a double shift cycle completes 11 times faster than an integer swap cycle. What property of doubles / integers makes them follow this path?

Test setup

  • Visual Studio 2012 x64
  • cpu core i7 950
  • Build as Release and run exe directly, VS Debug intercepts things

Output:

Process time for ints 1.438 secs

Process time for doubles 0.125 secs

 #include <iostream> #include <ctime> using namespace std; #define N 2000000000 void swap_i(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; } void swap_d(double *x, double *y) { double tmp = *x; *x = *y; *y = tmp; } int main () { int a = 1, b = 2; double d = 1.0, e = 2.0, iTime, dTime; clock_t c0, c1; // Time int swaps c0 = clock(); for (int i = 0; i < N; i++) { swap_i(&a, &b); } c1 = clock(); iTime = (double)(c1-c0)/CLOCKS_PER_SEC; // Time double swaps c0 = clock(); for (int i = 0; i < N; i++) { swap_d(&d, &e); } c1 = clock(); dTime = (double)(c1-c0)/CLOCKS_PER_SEC; cout << "Process time for ints " << iTime << " secs" << endl; cout << "Process time for doubles " << dTime << " secs" << endl; } 

It seems that VS only optimized one of the loops, as Blastfurnace explained.

When I turn off all compiler optimizers and turn on my swap code inside loops, I got the following results (I also switched my timer to std :: chrono :: high_resolution_clock):

Process time for ints 1449 ms

Process time for doubles 1248 ms

+7
source share
1 answer

You can find the answer by looking at the created assembly.

Using Visual C ++ 2012 (32-bit version of the assembly), the swap_i body is three mov commands, but the swap_d body swap_d fully optimized to an empty loop. The compiler is smart enough to see that an even number of swaps has no visible effect. I do not know why it does not do the same with the int loop.

Just changing #define N 2000000000 to #define N 2000000001 , and the recovery causes the swap_d body swap_d do the actual work. The final times on my machine are close, and swap_d about 3% slower.

+10
source

All Articles