以下のコードでは、スレッドプール経由で何度も関数を呼び出しています。この機能の中で、FastestMemoryと呼ばれるグローバルアトリビュートを介して、関数の最速実行を追跡します。Executorサービスと非常に高速なJavaコードの終了?
しかし、スレッドプールループの後に値を出力すると、ループ変数ごとにグローバル変数が更新される変数と同じでないように、元の値が与えられます。 FastestMemoryの値が(たとえば)253475に割り当てられていることがわかったときに、2000000000が返されただけです。
1)このコードを再構成して、最も速いものを追跡できるようにする必要がありますか繰り返し?
2)私はこのコードを非常に速く実行できるようですが、4つのXeon x7550で1イタレーション当たり1ミリ秒以下です。これは正常なのですか、どこかでタイミングが間違っていますか? C#は平均で約400ミリ秒かかりますか?
public class PoolDemo {
static long FastestMemory = 2000000000;
static long SlowestMemory = 0;
static long TotalTime;
static long[] FileArray;
static DataOutputStream outs;
static FileOutputStream fout;
public static void main(String[] args) throws InterruptedException, FileNotFoundException {
int Iterations = Integer.parseInt(args[0]);
int ThreadSize = Integer.parseInt(args[1]);
FileArray = new long[Iterations];
fout = new FileOutputStream("server_testing.csv");
// fixed pool, unlimited queue
ExecutorService service = Executors.newFixedThreadPool(ThreadSize);
ThreadPoolExecutor executor = (ThreadPoolExecutor) service;
for(int i = 0; i<Iterations; i++) {
Task t = new Task(i);
executor.execute(t);
}
executor.shutdown();
service.shutdown();
System.out.println("Fastest: " + FastestMemory);
for(int j=0; j<FileArray.length; j++){
new PrintStream(fout).println(FileArray[j] + ",");
}
}
private static class Task implements Runnable {
private int ID;
static Byte myByte = 0;
public Task(int index) {
this.ID = index;
}
@Override
public void run() {
long Start = System.nanoTime();
int Size1 = 100000;
int Size2 = 2 * Size1;
int Size3 = Size1;
byte[] list1 = new byte[Size1];
byte[] list2 = new byte[Size2];
byte[] list3 = new byte[Size3];
for(int i=0; i<Size1; i++){
list1[i] = myByte;
}
for (int i = 0; i < Size2; i=i+2)
{
list2[i] = myByte;
}
for (int i = 0; i < Size3; i++)
{
byte temp = list1[i];
byte temp2 = list2[i];
list3[i] = temp;
list2[i] = temp;
list1[i] = temp2;
}
long Finish = System.nanoTime();
long Duration = Finish - Start;
FileArray[this.ID] = Duration;
TotalTime += Duration;
System.out.println("Individual Time " + this.ID + " \t: " + (Duration) + " nanoseconds");
if(Duration < FastestMemory){
FastestMemory = Duration;
}
if (Duration > SlowestMemory)
{
SlowestMemory = Duration;
}
}
}
}
ありがとうございます!私のタイミングに関する問題はありますか? – mezamorphic
'long '値を変更するために、同期化に関するコメントを追加するように編集しました。同期ブロックは遅くなりますが、AtomicLongは高速ですが使用するのが難しくなります。 –
Upvoted、良いキャッチが、コードに別の問題があります。 –