[英]Java parallel matrix multiplication
有人可以帮我解决这个问题吗? 我正在尝试使用并行编程 - Java 进行矩阵乘法。 这是我迄今为止尝试过的
public class MatrixParallel22 extends Thread{
final static int noThreads = 2 ;
public static void main(String args[]) throws Exception{
//get the start time
long startTime = System.currentTimeMillis();
MatrixParallel [] threads = new MatrixParallel [noThreads] ;
for(int me = 0 ; me < noThreads ; me++) {
threads [me] = new MatrixParallel(me) ;
threads [me].start() ;
}
for(int me = 0 ; me < noThreads ; me++) {
threads [me].join() ;
}
long endTime = System.currentTimeMillis();
System.out.println("Calculation completed in " +
(endTime - startTime) + " milliseconds");
}
int me ;
public MatrixParallel(int me) {
this.me = me ;
}
public void run() {
//generate two matrices using random numbers
int matrix1 [][] = matrixGenerator();
int matrix2 [][] = matrixGenerator();
//get the number of rows from the first matrix
int m1rows = matrix1.length;
//get the number of columns from the first matrix
int m1cols = matrix1[0].length;
//get the number of columns from the second matrix
int m2cols = matrix2[0].length;
//multiply the matrices and put the result in an array
int[][] result = new int[m1rows][m2cols];
for (int i=0; i< m1rows; i++){
for (int j=0; j< m2cols; j++){
for (int k=0; k< m1cols; k++){
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
public static int[][] matrixGenerator(){
//create an array
int matrix [][] = new int[550][550];
//create a random generator
//and fill it with random numbers
Random r = new Random( );
for(int i=0; i < matrix.length; i++){
for(int j=0; j < matrix[i].length; j++){
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
}
在这种情况下,我试图在变量中设置线程数,然后在增加/减少线程数时测量并查看程序的执行速度。
//更新——当我执行代码时..它工作正常。 但问题是,如果我增加线程数,执行时间会变慢。 例如,对于 2 个线程,我得到 316 毫秒,而对于 8 个线程,我得到 755 毫秒,我不知道哪个部分是错误的。 这是我执行线程的方式吗?
当您使用更多线程时,完全可以预期您的程序不会运行得更快,因为您在每个单独的工作程序中创建新的乘法矩阵。 您不会将任务拆分为可由不同工作线程并行处理的多个部分。
至于在 Java 中加速一个简单的矩阵乘法实现,有很多类似的问题都有很好的答案(比如Peter Lawrey 在此处的回答)。
如果您实际上正在使用那么大的矩阵 ( n
> 500),您也可以尝试Strassen 算法。 当然,任何用于矩阵乘法的专门工具都会使简单的 Java 实现变得毫无意义,但我假设您这样做部分是为了好玩,部分是作为练习。
编辑:
看起来您不确定如何拆分和(尝试)并行化任务。 最明显的分治策略需要将每个矩阵分成 4 个象限,并将n
维矩阵的 1 次乘法转换为n/2
维矩阵的 8 次乘法,大致如下:
A11 | A12 B11 | B12 A11*B11 | A11*B12 A12*B21 | A12*B22
|----+----| x |----+----| = |--------+--------| + |---------+-------|
A21 | A22 B21 | B21 A21*B11 | A21*B21 A22*B21 | A22*B22
Strassen 的算法可以将其减少到 7 次乘法,使用非常精确地选择的 A ij和 B ij矩阵操作。
您还可以将使用多线程获得的加速与精心选择的数组迭代顺序的加速进行比较(请参阅此处的 Wayne 和 Sedgewick 插图)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.