我想写一个超级简单的C程序的矢量乘 - 加“axpy”算法的整数数据类型。程序输出执行时间来测量机器的性能。矩阵由随机数填充。当两个矩阵大小超过800×800
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(int的大小)= 3,200,000。这是一个很大的**内存分配作为本地变量,它可能由于缺乏堆栈空间而失败。把它放在堆上。 –