在执行具有小精度浮点数的算术运算时,我检测到异常的计算时间。以下简单代码展示了这种行为:
#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.32000segsy = 0.9
x = 0.000000
时间:19.99000segs
我正在使用具有以下规格的笔记本电脑来测试代码:
- CPU : Intel® Core™2 Duo CPU T5800 @ 2.00GHz × 2
- 内存:4 GB
- 操作系统:Ubuntu 12.04(64 位)
- 型号:戴尔工作室 1535
有人可以详细解释为什么会发生这种行为吗?我知道 y = 0.9 时 x 值变为 0 的速度比 y = 0.5 时要慢,所以我怀疑问题与此直接相关。