【发布时间】:2020-09-24 06:06:37
【问题描述】:
我的主要目的是通过在各种环境中对 C 和 Java 中的矩阵乘法算法进行基准测试来展示虚拟化与容器化的不同之处,并得出一个合适的结论。
我选择这个算法的原因是因为矩阵乘法是各种计算机科学领域中非常常用的算法,因为它们中的大多数都处理大尺寸,我希望优化我的代码以能够执行高达至少 2000x2000 矩阵大小,这样两者之间的差异就很明显了。
我在 Linux 上使用 GCC,在 Windows 上的 Code::Blocks 中使用 C 的默认编译器(我不知道使用的是哪个版本的 GCC)。
问题是,当我在 Windows 上运行代码时,编译器只接受最大为 490x490 的大小,如果超过该大小,则转储内核。 Linux 设法克服了这个问题,但不能超过 590x590。
我一开始以为是我的设备内存造成的,于是请了几个机器好很多的朋友运行同样的代码,结果还是一样。
仅供参考:我正在运行 Pentium N3540 和 4GB DDR3 RAM。我的朋友们正在运行带有 16GB DDR4 的 i7-8750H,而另一个使用带有 8GB DDR4 的 i5-9300H。
这是我写的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int main()
{
long i, j, k, m, n;
printf("Enter the row dimension of the matrix: "); scanf("%ld", &m);
printf("Enter the column dimension of the matrix: "); scanf("%ld", &n);
long mat1[m][n], mat2[m][n], mat3[m][n];
for(i=0; i<m; i++)
for(j=0; j<n; j++)
{
mat1[i][j] = (long)rand()%MAX;
mat2[i][j] = (long)rand()%MAX;
mat3[i][j] = 0;
}
printf("\n\nThe matrix 1 is: \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d\t", (int)mat1[i][j]);
}
printf("\n");
}
printf("\n\nThe matrix 2 is: \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d\t", (int)mat2[i][j]);
}
printf("\n");
}
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
for (k = 0; k < n; k++)
mat3[i][j] += mat1[i][k] * mat2[k][j];
printf("\n\nThe resultant matrix is: \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d\t", (int)mat3[i][j]);
}
printf("\n");
}
return 0;
}
【问题讨论】:
-
使用堆而不是栈。参见 malloc
-
有关您的问题的解释,请参阅本网站的名称 :-)
-
将
m乘以n以获得mat1、mat2和mat3中的每一个所需的元素数。乘以3以获得所有三个矩阵的元素总数。乘以sizeof(long)(即 4 或 8)以获得所有数组所需的字节大小。将该大小与系统上堆栈的标准大小(Linux 上 8 MiB,Windows 上 1 MiB)进行比较。这应该可以帮助您了解问题所在。 -
用
printf("%d\t", (int)mat3[i][j]);代替printf("%ld\t", mat3[i][j]); -
mat1[i][j]的值应该是 0 到MAX还是 0 到MAX-1?
标签: c matrix optimization matrix-multiplication