我发现在使用小精度的浮点数进行算术运算时存在不寻常的计算时间。以下简单的代码展示了这种行为:
#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.32000秒y = 0.9时:
x = 0.000000
时间:19.99000秒
我使用以下规格的笔记本电脑测试代码:
- CPU: Intel® Core™2 Duo CPU T5800 @ 2.00GHz × 2
- 内存: 4 GB
- 操作系统: Ubuntu 12.04 (64 bits)
- 型号: Dell Studio 1535
有人可以详细解释一下这种行为发生的原因吗?我知道当y = 0.9时,x值下降得比y = 0.5慢,所以我认为问题直接与此有关。