我试图使用以下程序以编程方式了解缓存的影响.我正在使用代码获得段错误.我使用了GDB(用-g -O0编译),发现它是分段错误
start = clock() (first occourance)
#include dio.h>
#include cpu_time;
int i = 0;
int arr[MAX_SIZE];
/* cpu clock ticks count start */
start = clock();
/* Loop 1 */
for (i = 0; i < MAX_SIZE; i++)
arr[i] *= 3;
/* cpu clock ticks count stop */
end = clock();
cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("cpu time for loop 1 %.6f secs.\n",cpu_time);
/* cpu clock ticks count start */
start = clock();
/* Loop 2 */
for (i = 0; i < MAX_SIZE; i += 16)
arr[i] *= 3;
/* cpu clock ticks count stop */
end = clock();
cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("cpu time for loop 2 %.6f secs.\n",cpu_time);
return 0;
}
最佳答案
尝试改变:
int arr[MAX_SIZE];
至:
int *arr = (int*)malloc(MAX_SIZE * sizeof(int));
正如Potatoswatter建议的那样,数组对于堆栈来说可能太大了……你可能在堆上分配,而不是在堆栈上分配…