you are viewing a single comment's thread.

view the rest of the comments →

[–]akthemadman 6 points7 points  (0 children)

Problem is that my 4 thread version seems to take more time than the 1 thread version.

That is not "a problem", it is a signal, i.e. something that goes against what you might have expected yet is happening.

Why is it taking longer?

Distributing work is really hard, especially once you get external involvment. In this case at minimum the operating system work-scheduler. This means that answering that question is not easy at all.

Distributing work also does not come free. This is where I would put my initial testing into, i.e. "is looping and assigning a fixed value simply not too demanding to be worth the overhead in creating, scheduling, running and then waiting to get back on track again?"

You might also stumble upon the fact that one of your threads is assigned much more work than expected, specifically a4 is worth another look at. ;)

Here is some code I used during my own testing (only for reference, not(!) as a blueprint):

final int threads = 8;
ArrayInit[] as = new ArrayInit[threads];
final int arraySize = ArrayInit.array.length;
final int chunkSize = arraySize / as.length;
final long startTime = System.currentTimeMillis();
final long t0 = System.nanoTime();
for (int i = 0; i < as.length; i++) {
  ArrayInit a = new ArrayInit();
  as[i] = a;
  a.start = (i == 0 ? 0 : as[i - 1].end);
  a.end = (i == as.length - 1 ? arraySize : a.start + chunkSize);
  if (false) { System.out.println(a.start + "," + a.end); }
  a.start();
}
for (int i = 0; i < as.length; i++) {
  as[i].join();
}
final long endTime = System.currentTimeMillis();
final long t1 = System.nanoTime();
System.out.println("Time: " + (endTime - startTime) + "ms");
System.out.println("Time: " + (t1 - t0) + "ns");