我需要計算一個64位數(n = pq)。 所以我實現了一個方法,它必須搜索範圍[1; SQRT(N)]。執行2個或多個Runnables會導致性能問題
在1,2 GHz處理器的Android上執行需要27秒鐘(不幸的是,我不知道一些CPU內核)。所以我決定把它平行。那麼,兩個Runnables
給我的結果在51秒和3 - 在83.
我的程序只是在onCreate
做什麼,只是調用此方法。
final static private int WORKERS_COUNT = 3;
final static public int[] pqFactor(final long pq) {
stopFactorFlag = false;
long blockSize = (long)Math.ceil(Math.sqrt(pq)/WORKERS_COUNT);
ExecutorService executor = Executors.newFixedThreadPool(WORKERS_COUNT);
for (int workerIdx = 0; workerIdx < WORKERS_COUNT; ++workerIdx) {
Runnable worker = new FactorTask(pq, workerIdx * blockSize, (workerIdx + 1) * blockSize);
executor.execute(worker);
}
executor.shutdown();
try {
executor.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
private static boolean stopFactorFlag;
private static int p, q;
static private class FactorTask implements Runnable {
final private long pq;
private long leftBorder;
private long rightBorder;
public long pInternal;
public long qInternal;
/* Constructor was there */
@Override
public void run() {
for (qInternal = rightBorder; !stopFactorFlag && qInternal > leftBorder && qInternal > 1L; qInternal -= 2L) {
if (pq % qInternal == 0L) {
pInternal = pq/qInternal;
p = (int)pInternal;
q = (int)qInternal;
stopFactorFlag = true;
break;
}
}
}
}
P. S.這不是一個家庭作業,我真的需要這個。也許是另一種方式。
當你多線程的問題時,你的'for'循環中的條件會變得很糟糕。優化之後,'x - = 2L'的方式比'x - '慢,並且額外的停止標誌也會增加開銷。這些可能是問題的一部分 – torquestomp