[英]Why is my Android Thread so Slow?
我一直在嘗試編寫一種撲克計分算法...該算法具有七個嵌套的for循環,以循環遍歷七張紙牌撲克手的每種組合並對它們進行評分。 當然,這是一個非常密集的循環……只有不到1.105億個組合。
我的算法尚在開發中,尚待完成……但是在桌面上的Eclipse中,我們設法在大約8.5秒內正確得分了所有手部組合。 不錯,我想...但是Android線程中的相同算法在Android仿真器上花費17分鍾,在HTC One XL上花費4分鍾。
我已經為手機的運行速度比新的台式機做好了充分的准備...但是不超過30倍。
我的代碼如下;
public void startThread() {
Runnable runnable = new Runnable()
{
String bitString;
byte[] bitCount = new byte[8192];
byte[] isStraight = new byte[8192];
boolean[] isFlush = new boolean[8912];
int c, c1, c2, c3, c4, c5, c6, c7;
int[] cards = new int[7];
long sTime, eTime, score = 0;
int[] handCount = new int[9];
int pipMask;
int[] pips = new int[6];
int[] suit = new int[4];
@Override
public void run()
{
for (c = 0; c < 8192; c++)
{
bitString = String.format("%13s", Integer.toBinaryString(c)).replace(" ","0");
}
sTime = System.currentTimeMillis();
pips[0] = 8191;
for (c1 = 0; c1 < 46; c1++) {
for (c2 = c1 + 1; c2 < 47; c2++) {
for (c3 = c2 + 1; c3 < 48; c3++) {
for (c4 = c3 + 1; c4 < 49; c4++) {
for (c5 = c4 + 1; c5 < 50; c5++) {
for (c6 = c5 + 1; c6 < 51; c6++) {
for (c7 = c6 + 1; c7 < 52; c7++) {
--- code goes here ---
}}}}}}}
eTime = System.currentTimeMillis(); Log.d("end", "" + (eTime - sTime));
message = handler.obtainMessage();
bundle = new Bundle();
bundle.putString("msgText", "Finished in " + (eTime - sTime));
message.setData(bundle);
handler.sendMessage(message);
} // end run()
}; // end runnable
Thread myThread = new Thread(runnable); myThread.start();
} // end
我在Android中實現線程做錯了嗎?
我擔心這可能是字節數組和布爾數組的大小以及對線程施加的某種內存限制嗎?
問題不在於線程。
問題不在於內存使用量...因為它看起來相對較小,並且(AFAIK)在完成工作的代碼部分中沒有更改。
真正的問題是,您有一個7級深循環,每個變量的范圍都很大,並且您在循環內做了很多工作。
(提示:46 * 47 * 48 * 49 * 50 * 51 * 52 ...是一個相當大的數字。)
基本上,您的PC可以比普通手機更快地運行Java代碼。 我認為30倍是合理的。
要考慮的一件事是,與典型的Android JIT編譯器相比,HotSpot JVM中的JIT編譯器更加復雜並且更具攻擊性。 如果有的話,那將擴大硬件性能的差異。
謝謝你們。 一旦很清楚,我在Android中使用線程的方式並沒有天生的錯誤,我就提出了將代碼移植到NDK / C ++的建議。 現在快得多了; 21秒和240秒
即。 超過10倍。
仍然不夠快,無法制作出有用的應用程序...但是嘗試很有趣。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.