希望我能说清楚自己。
我正在尝试测量这个程序将多个矩阵相乘并将结果存储到另一个矩阵中的时间(称为C)。
我需要记录从1到100,1到200,1到300等的时间
我实际上是在测量时间并将结果存储到.dat文件中以便稍后进行绘图(使用gnuplot)
事情是......当我运行它时,我只得到最后一次迭代N次我想测量。假设我尝试从1到100,我确实得到100次迭代,但在.dat文件中,我只得到最后一次迭代。如果我不清楚,我很抱歉。
这是代码,希望你能理解。谢谢!!
import java.util.Timer;
import java.util.Scanner;
public class matrixMult
{
public static void main(String[] args)
{
//Creating a new Scanner to get input from Stdin//
Scanner input = new Scanner(System.in);
//Creates a variable to store the NxN dimension of the Matrices//
int ms = input.nextInt();
//Initializing Matrices and giving them the dimensions provided by the Stdin//
int [] [] A = new int [ms] [ms];
int [] [] B = new int [ms] [ms];
int [] [] C = new int [ms] [ms];
//Populating the Matrices with 1's and 0's//
populatingMatrices (A);
populatingMatrices (B);
//Closing the Scanner after being used//
input.close();
long t_start;
long t_end;
long t_cost = 00000000000L;
for (int x = 0; x < ms ;x++ )
{
//Starts the timer//
t_start = System.nanoTime();
//Storing the result of the matrices multiplication into C//
C = mmm(A,B,C);
//End the timer
t_end = System.nanoTime();
t_cost = t_end - t_start;
System.out.println();
System.out.println((t_cost / 1000000.0));
}
}//Main Method//
//Method to populate Matrices with 1's and 0's//
public static int [][] populatingMatrices(int A [] [])
{
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[0].length; j++)
{
if (i == j)
{
A[i][j] = 1;
}
else
{
A[i][j] = 0;
}
}
//Returns Matrix populated with 1's accross the diagonal axis, and 0's in all other elements of the Matrix//
}return A;
}
//Method to multiply Identity Matrices//
public static int [][] mmm (int a [][], int b [][], int c [][])
{
int nr;
int nc;
nr = nc = a.length;
for (int i = 0; i < nr; i++)
{
for (int j = 0; j < nr ; j++ )
{
for (int k = 0;k < nr ;k++)
{
c[i][j] = c[i][j] + a[i][j] * b[k][j];
}
}
}
return c;
}
}
非常感谢!
答案 0 :(得分:0)
您只是获取最近一次迭代的最后一次,因为您不断覆盖t_cost的值。你需要做一个+ =来为你的for循环的每次迭代添加它。
long t_start;
long t_end;
long t_cost = 00000000000L;
for (int x = 0; x < ms ;x++ )
{
//Starts the timer//
t_start = System.nanoTime();
//Storing the result of the matrices multiplication into C//
C = mmm(A,B,C);
//End the timer
t_end = System.nanoTime();
//use the += so you are adding to the previous iterations of your calcualted time
t_cost += t_end - t_start;
System.out.println();
System.out.println((t_cost / 1000000.0));
}
答案 1 :(得分:0)
我认为for循环中的“ms”应该是你希望for循环运行多少次。我无法理解为什么它与您在上面的代码中设置的数组大小相关联。
ArrayList<long> al = new ArrayList()
al.add(System.nanoTime());//Start time;
for (int x = 0; x < ms ;x++ )
{
//Storing the result of the matrices multiplication into C//
C = mmm(A,B,C);
if(x == 100 || x == 200)
{
al.add(System.nanoTime());//at given points time
}
}
al.add(System.nanoTime());//end time. if You end at a point that you check in the if statment like 200, then this is not needed.
//now do your cost calculations using all the values stored in al.