0

Java Othello プログラムからすべてを絞り出そうとしていますが、特定の数値が表示されるインスタンスの数をカウントする必要があるポイントがあります。たとえば、array[]{1,1,2,1,0,1} は count(1) で 4 を返します。以下は、すべての数値をカウントすることで高速に試みましたが、これは遅くなりました。

public void count(int color) { 
    byte count[] = new byte[3];

    for (byte i = 0; i < 64; i++)
        ++count[state[i]];

    return count[color];
}

これまでのところ、これは私がテストした最も効率的なコードです:

public void count(int color) {  
    byte count = 0;

    for (byte i = 0; i < 64; i++) 
        if (this.get(i) == color)
            count++;

    return count;
}

これでもっとスピードを絞り出せると思う人はいますか?指定された数のカウントのみが必要です。それ以上は必要ありません。

4

4 に答える 4

2

一部のアーキテクチャではシングルの処理intに問題があるため、メモリ内のバイトは小さくなりますが、計算には問題があります。bytebytes

于 2013-04-25T04:27:00.193 に答える
2

Use int, not byte - internally, Java converts the byte to an int, then increments it, then converts it back to a byte; using an int obviates the need for the type conversions.

You can also try using an AtomicInteger, its getAndIncrement method may be faster than the ++ operator.

You can also unroll your loop; this will reduce the number of times that i < 64 is evaluated. Try using an AtomicInteger for i, and use getAndIncrement instead of ++

for(int i = 0; i < 64;) {
    if(this.get(i++) == color) ...
    if(this.get(i++) == color) ...
    if(this.get(i++) == color) ...
    if(this.get(i++) == color) ...
}

Changing the for loop to a do-while loop may be slightly faster - the for loop has a conditional jump and an unconditional jump, but a do-while loop only has a conditional jump.

You can do this in parallel (thread1 counts elements 0-15, thread2 counts elements 16-31, etc), but the cost of creating the threads probably isn't worth it.

于 2013-04-25T04:28:34.290 に答える
0

1) バージョン 2 の this.get(i) は疑わしいようです。配列を扱う場合は、array[i] の方が効率的であるはずです。

2) 交換します

byte count = 0;
for (byte i = 0; i < 64; i++) 
... 

int count = 0;
for (int i = 0; i < 64; i++) 
... 

それ以外の場合、Java はバイトオペランドを int にプロモートして算術を実行し、結果をバイトに切り詰める必要があります。

3) http://code.google.com/p/caliper/を使用して、適切なベンチマークを取得します

于 2013-04-25T04:53:19.467 に答える