性能交换整数与双精度
Performance swapping integers vs double
出于某种原因,我的代码能够比在整数上更快地对双精度执行交换。我不知道为什么会发生这种情况。
在我的机器上,双交换循环的完成速度比整数交换循环快 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%。
相关文章:
- 我可以信任表示整数的浮点或双精度来保持精度吗
- C 字符串返回字符串的整数/双精度/长整型值
- 如何防止双精度值到整数的隐式转换
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- 为什么输出是整数而不是双精度?
- 从字符串转换为双精度和整数 - C++
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- C++,遇到将双精度转换为整数的问题
- 用双精度除以整数
- 使用整数初始化列表初始化长双精度的向量
- 如何判断 c++ 向量中的值类型(整数或双精度)?
- 了解双精度转换与整数转换中的整数与截断关系
- 为什么使用 int64_t 会产生错误的结果,而双精度则按预期进行简单的整数乘法
- 将双精度与整数进行比较
- 64 位整数到双精度冲突
- 在编译时将整数和分数部分宏组合成一个新的宏或双精度
- 不确定输出双精度或整数的代码行
- 双精度/整数模板函数的向量
- 如何通过 JNI 设置 java 类的双精度/整数类型的值
- 将输入验证为双精度/整数的函数