Christian
Christian

Reputation: 241

No Speedup on Android DualCore Handy LG Optimus Speed with Java Threads?

I was playing around with the LG LG P990 optimus speed and noticed that I could not get any speedup at all using multiple threads.

I used the following code for to measure the time needed for some computations.

public class TestThreads extends Thread{

public void run()
{
double temp;
    for(int i = 0; i < 5000000 ;i++)
    {
        temp = Math.random()*Math.random();
    }
}

}

    long start = System.currentTimeMillis();
    Thread t1 = new TestThreads();
    Thread t2 = new TestThreads();
    t1.start();
    t2.start();
t1.join();
t2.join();

The resulting time I compared to the the needed to calculate

    for(int i = 0; i < 10000000 ;i++)
    {
        temp = Math.random()*Math.random();
    }

Since the 2 Threaded Version calculates the same amount of loops but distributed over 2 Threads which could possibly run parallel I expected this Version to be significantly faster. However there was no speedup at all and in some cases the Threaded Version was even slower. is there a problem with my idea / code or does Android not distribute multiple threads accross multiple CPU cores?

Upvotes: 1

Views: 303

Answers (2)

Luis Miguel Serrano
Luis Miguel Serrano

Reputation: 5099

First of all, whenever you use Threads you are increasing the amount of memory overhead, because of the additional objects you create and the memory that must be assigned for them within the java virtual machine.

Second, the fact you have 2 CPUs can be used and taken advantage of even in an application with a single Thread. This is true because even with the application being executed in a single processor, the other will be processing other tasks from other applications, consequently leaving the first one free during more time, and allowing a more continuous processing of your application.

In any case, it is the operating system that decides which application is processed at a given time, and in which processor it is processed.

But for those reasons, it is possible that in some occasions the overhead might not be worth the gain, even when using other methods which are thread safe, specially when there is much to be processed in the device. However, with a threadsafe method (unlike Math.random()), there should be gains, even if small, in a worst-case situation.

Upvotes: 0

smith324
smith324

Reputation: 13060

Math.random() is not thread safe, it has a mutex that controls access, which adds overhead and slows the threads down. You can read about it here http://code-o-matic.blogspot.com/2009/01/beware-of-hidden-contention-of.html

Try doing something else that is thread safe.

Upvotes: 2

Related Questions