[英]Java Multithreading Matrix Multiply
這是我的並行乘矩陣的代碼:
public void multiplyParallel() {
int numProcessors = Runtime.getRuntime().availableProcessors();
int step = (int)MATRIX_SIZE/numProcessors;
for (int i=0; i<numProcessors; i++) {
Runnable r = new MatrixMultiply(this.start, this.end);
new Thread(r).start();
this.start += step;
this.end += step;
}
this.start = 0;
this.end = 0;
}
@Override
public void run() {
for (int i=this.start; i<this.end; i++)
for (int j=this.start; j<this.end; j++)
for (int k=this.start; k<this.end; k++)
this.matrix3[i][j] = this.matrix1[i][k] * this.matrix2[k][j];
}
但是,當我在1024x1024矩陣上運行此代碼時,它僅運行2-3毫秒,而串行版本運行約1秒鍾。 我應該期望並行版本的最佳時間是1 /(numProcessors)時間。
我做錯了什么嗎? 調用run()方法的次數與我的計算機上存在處理器的次數相同。
我做錯了什么嗎?
是的 您沒有將矩陣相乘。 實際上,您實際上是在將矩陣切成子矩陣,然后將這些矩陣的子集與原始矩陣的對角線相乘。
我建議您比較兩個版本的計算結果...並從中得出自己的結論。
矩陣乘法的有效並行化不是一個簡單的問題。
這是幾個相關的鏈接,盡管是一般性的:
http://www.cs.berkeley.edu/~yelick/cs267-sp04/lectures/13/lect13-pmatmul-6x.pdf-從幻燈片17開始。
http://www.slideshare.net/pkpramit/matrix-multiplicationan-example-of-concurrent-programming
Java 6中的並行矩陣乘法 ...包括一些Java代碼(YMMV)。
還要注意,根據Wikipedia,比“幼稚”( O(N^3)
)乘法有更有效的非並行算法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.