java - Executing 2 or more Runnables causes performance issues -
i need factor 64-bit number (n = pq). implemented method searches consequentially numbers in range of [1; sqrt(n)].
it took 27 secs execute on android 1,2 ghz processor (unfortunately, don't know number of cpu cores). decided make parallel. well, 2 runnables
giving me results in 51 secs , 3 — in 83.
my program nothing calling method in 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); (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 there */ @override public void run() { (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. not homework, need this. maybe other way.
executing 2 or more runnables causes performance issues
this looks me android device has either 1 or 2 cores , adding threads problem not going make run faster because have exhausted cpu resources. i'd recommend looking device specs determine how many cores has.
if run code under 4 core macbook pro:
- 2 threads in ~6secs
- 3 threads in ~4secs
- 4 threads in ~3.5secs
this seems me reasonably linear (taking account startup/shutdown overhead) , indicates me not code holding back.
btw, stopfactorflag
should volatile
. don't see how creating result
array i'm worried race conditions there.
Comments
Post a Comment