性能交换整数与双倍

时间:2012-09-16 01:26:26

标签: 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;
}

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

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

Process time for ints 1449 ms

Process time for doubles 1248 ms

1 个答案:

答案 0 :(得分:10)

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

使用Visual C ++ 2012(32位版本构建)swap_i的正文是三条mov指令,但swap_d的正文已完全优化为空循环。编译器非常聪明,可以看到偶数个交换没有可见效果。我不知道为什么它与int循环没有相同。

只需将#define N 2000000000更改为#define N 2000000001并重建,即可让swap_d机构执行实际工作。最后一次在我的机器上很近,swap_d慢了约3%。

相关问题