出于某种原因,我的代码能够比整数更快地执行双精度对换。我不知道为什么会发生这种情况。性能交换整数与双倍
在我的机器上,双交换循环完成比整数交换循环快11倍。双/整数的属性使它们以这种方式执行?
测试设置
- 的Visual Studio 2012的x64
- CPU的Core i7 950
- 建设成为发布和exe文件直接运行,VS调试挂钩歪斜的事情
输出:
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优化环中的一个作为高炉解释。
当我禁用所有的编译器优化,并有我的环内交换代码内联,我得到的结果如下(我也切换我的定时器到std ::计时:: high_resolution_clock):
Process time for ints 1449 ms
Process time for doubles 1248 ms
输出是什么?我很好奇。还有,32位机器还是64位机器? 32位或64位代码?编译器? OS? – nneonneo
我们在这里谈了多少秒? –
什么是你的机器?我在这里用几种不同的优化方式运行你的程序,而我没有得到任何你所看到的东西。缓存行为可能? –