性能交换整数与双精度

Performance swapping integers vs double

本文关键字:双精度 整数 能交换 性能      更新时间:2023-10-16

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

在我的机器上,双交换循环的完成速度比整数交换循环快 11 倍。双精度/整数的什么属性使它们以这种方式执行?

测试设置

  • Visual Studio 2012 x64
  • 中央处理器酷睿 i7 950
  • 构建为发布并直接运行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似乎只优化了其中一个回路,正如Heart所解释的那样。

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

Process time for ints 1449 ms

Process time for doubles 1248 ms

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

使用 Visual C++ 2012(32 位发布版本),swap_i的主体是三个mov指令,但swap_d主体完全优化为空循环。编译器足够聪明,可以看到偶数次交换没有可见的影响。我不知道为什么它对int循环不做同样的事情。

只需将#define N 2000000000更改为#define N 2000000001并重建,swap_d机构就会执行实际工作。我的机器上的最后时间已经接近,swap_d慢了大约 3%。