由于某种原因,我的代码能够比整数更快地对双精度数执行交换。我不知道为什么会这样。
在我的机器上,双交换循环的完成速度比整数交换循环快 11 倍。双精度/整数的什么属性使它们以这种方式执行?
测试设置
- 视觉工作室 2012 x64
- 处理器核心 i7 950
- 构建为 Release 并直接运行 exe,VS Debug hooks 歪曲了事情
输出:
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;
}
正如 Blastfurnace 解释的那样,VS 似乎只优化了其中一个循环。
当我禁用所有编译器优化并将交换代码内联在循环中时,我得到以下结果(我还将计时器切换到 std::chrono::high_resolution_clock):
Process time for ints 1449 ms
Process time for doubles 1248 ms