性能交换整数与双倍

sma*_*rne 7 c++ compiler-optimization

出于某种原因,我的代码能够比双整数更快地执行双向交换.我不知道为什么会发生这种情况.

在我的机器上,双交换循环比整数交换循环快11倍.双打/整数的哪些属性使它们以这种方式执行?

测试设置

  • Visual Studio 2012 x64
  • cpu core i7 950
  • 构建为Release并直接运行exe,VS Debug挂钩事物

输出:

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;
}
Run Code Online (Sandbox Code Playgroud)

似乎VS只优化了其中一个循环,正如Blastfurnace所解释的那样.

当我禁用所有编译器优化并让我的交换代码内联在循环中时,我得到了以下结果(我还将我的计时器切换到std :: chrono :: high_resolution_clock):

Process time for ints 1449 ms

Process time for doubles 1248 ms

Bla*_*ace 10

您可以通过查看生成的程序集找到答案.

使用Visual C++ 2012(32位版本构建),主体swap_i是三个mov指令,但主体swap_d完全优化到一个空循环.编译器非常聪明,可以看到偶数个交换没有可见效果.我不知道为什么它不会对int循环做同样的事情.

只是改变#define N 2000000000#define N 2000000001和重建会导致swap_d身体进行实际的工作.最后的时间在我的机器上很接近,swap_d慢了大约3%.