【发布时间】:2018-03-18 20:50:32
【问题描述】:
我正在尝试为整数数据类型编写一个向量乘加“axpy”算法的超级简单的 C 程序。程序输出执行时间来衡量机器的性能。矩阵由随机数填充。
int benchmark(void) {
int N; /* The matrix size, controlled by user input */
int r, c; /* Row and Column number */
int random; /* Random number to fill the matix */
int a = rand() % 20; /* Scale number to multiply x matrix */
printf("Enter the size(N*N) of the matrices(Maximum 1,000,000)\n");
scanf("%d", &N);
if (N > 1000000) {
fprintf(stderr, "Size of matrix is too large!\n");
return 0;
}
/* Initialize and fill the matrix x and y */
int xMatrix[N][N], yMatrix[N][N], resultMatrix[N][N];
/* Compute time */
clock_t t;
t = clock();
for (r = 0; r < N; r++) {
for (c = 0; c < N; c++) {
random = rand() % 100;
xMatrix[r][c] = a * random; /* Multiply matrix x with random value a */
}
}
for (r = 0; r < N; r++) {
for (c = 0; c < N; c++) {
int random = rand() % 100;
yMatrix[r][c] = random;
}
}
/* Add two matrix together */
for (r = 0; r < N; r++) {
for (c = 0; c < N; c++) {
resultMatrix[r][c] = xMatrix[r][c] + yMatrix[r][c];
}
}
t = clock() - t;
double timeTaken = ((double)t) / CLOCKS_PER_SEC;
printf("\n -> Total time : %f seconds\n", timeTaken);
printf("\n -> Vector length : %d", N * N);
}
用户控制矩阵的大小。
当N 的值小于800 时,程序运行良好。
【问题讨论】:
-
您的堆栈可能已用完。考虑使用 malloc 动态分配数组。
-
800*800=640,000。 x4(整数大小)= 3,200,000。这是作为局部变量分配的很多内存,它可能由于堆栈空间不足而失败。而是把它放在堆上。
标签: c arrays segmentation-fault