【发布时间】:2012-09-05 19:02:48
【问题描述】:
我在执行具有小精度浮点数的算术运算时检测到异常的计算时间。以下简单代码展示了这种行为:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
const int MAX_ITER = 100000000;
int main(int argc, char *argv[]){
double x = 1.0, y;
int i;
clock_t t1, t2;
scanf("%lf", &y);
t1 = clock();
for (i = 0; i < MAX_ITER; i++)
x *= y;
t2 = clock();
printf("x = %lf\n", x);
printf("Time: %.5lfsegs\n", ((double) (t2 - t1)) / CLOCKS_PER_SEC);
return 0;
}
这是程序的两种不同运行方式:
-
当 y = 0.5
x = 0.000000
时间:1.32000segs -
当 y = 0.9
x = 0.000000
时间:19.99000segs
我正在使用具有以下规格的笔记本电脑来测试代码:
- CPU:Intel® Core™2 Duo CPU T5800 @ 2.00GHz × 2
- 内存:4 GB
- 操作系统:Ubuntu 12.04(64 位)
- 型号:Dell Studio 1535
有人可以详细解释为什么会发生这种行为吗?我知道 y = 0.9 时 x 值变为 0 的速度比 y = 0.5 时要慢,所以我怀疑问题与此直接相关。
【问题讨论】:
-
在达到 0 之前,您可能会在第二种情况下获得更多的非正规化。
-
另请参阅this answer,了解非规范化对性能的影响。
标签: c performance time