我正在开发一个测试不同矩阵乘法方法的项目。目标是测试 1000 组数据,每组 20 次,对于 n x n 矩阵,最大 n = 2^i,在我的例子中,我将最大 n = 256。
我的矩阵乘法方法都工作得很好,但我无法让它测试正确的次数。 下面是我的主要方法,我试图在其中测试此功能的输出正确性。
public static void main(String[] args)
{
final int SETS = 1;
final int TIMES = 2;
final int POWER = 1;
long timeStart, timeEnd;
long totalTimeClassical = 0;
long totalTimeDivideConquer = 0;
long totalTimeStrassen = 0;
long avgTimeClassical = 0;
long avgTimeDivideConquer = 0;
long avgTimeStrassen = 0;
int[][] a, b;
int n;
for (int i=1; i<=POWER; i++)
{
n = (int) Math.pow(2, i);
for (int j=1; j<=TIMES; j++)
{
for (int k=1; k<=SETS; k++)
{
a = buildMatrix(n);
b = buildMatrix(n);
timeStart = System.nanoTime();
classicalMatrixMult(a, b, n);
timeEnd = System.nanoTime();
totalTimeClassical += timeEnd - timeStart;
timeStart = System.nanoTime();
divideConquerMatrixMult(a, b, n);
timeEnd = System.nanoTime();
totalTimeDivideConquer += timeEnd - timeStart;
timeStart = System.nanoTime();
strassenMatrixMult(a, b);
timeEnd = System.nanoTime();
totalTimeStrassen += timeEnd - timeStart;
outputMatrix(a,n);
outputMatrix(b,n);
System.out.println(" -----------");
}
totalTimeClassical = totalTimeClassical / TIMES;
totalTimeDivideConquer = totalTimeDivideConquer / TIMES;
totalTimeStrassen = totalTimeStrassen / TIMES;
}
avgTimeClassical = totalTimeClassical / SETS;
avgTimeDivideConquer = totalTimeDivideConquer / SETS;
avgTimeStrassen = totalTimeStrassen / SETS;
System.out.print("For " + n + "x" + n + ":");
System.out.println("\nClassical Matrix multiplication took "
+ avgTimeClassical + " nanoseconds to run."
+"\nDivide and Conquer Matrix multiplcation took "
+ avgTimeDivideConquer + " nanoseconds to run."
+"\nStrassen's Matrix Multiplication took "
+ avgTimeStrassen + " nanoseconds to run."
+ "\n");
}
}
上面是我的主要方法,我目前将其设置为打印输入矩阵,以便我可以查看它是否使用正确数量的数据集运行了正确的次数。使用我插入的当前值,我希望它测试 1 组 2 x 2 矩阵 2 次。相反,它测试 2 组 2 x 2 矩阵,因为打印输出的值不同。
9 -9
-4 4
-2 0
3 8
-----------
-5 10
-1 1
-2 -8
-5 -5
-----------
For 2x2:
Classical Matrix multiplication took 2514 nanoseconds to run.
Divide and Conquer Matrix multiplcation took 10575 nanoseconds to run.
Strassen's Matrix Multiplication took 1356 nanoseconds to run.
我尝试重新排列循环,但最终破坏了代码。如何格式化它以便它测试一组数据指定的次数?
最佳答案
看来您对矩阵创建和时间循环的排序不正确。
首先,您需要为“SETS”值的数量创建矩阵的数量。 然后在该循环内,您需要运行“TIMES”次数的操作。
for (int i=1; i<=POWER; i++)
{
n = (int) Math.pow(2, i);
for (int j=1; j<=SETS; j++)
{
a = buildMatrix(n);
b = buildMatrix(n);
for (int k=1; k<=TIMES; k++)
{
// operations code
}
}
}
关于java - 如何对 nxn 矩阵(最多 n=2^i)测试 1000 组数据,每组数据 20 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64550351/