Jim
Jim

Reputation: 9234

Multi-threading for multi-core processors

I have Samsung Galaxy S3, which used its own Exynos 4 Quad processor. So I want to optimize my app, that it can use all 4 cores of processor.

So I made some tests:

  1. Run task in one thread. Processing time - 8 seconds.

  2. Run task in four threads. Processing time - still 8 sec.

     new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
    new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
    new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
    new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
  3. Run task in ExecutorService. And processing time - still 8 sec.

    ExecutorService threadPool = null;
    threadPool = Executors.newFixedThreadPool(4);
    
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    

Looks like all work done synchronously. Why its not paralleling ?

Upvotes: 3

Views: 2436

Answers (1)

fadden
fadden

Reputation: 52323

You can try my tests, in C or Java:

http://bigflake.com/cpu-spinner.c.txt
http://bigflake.com/MultiCore.java.txt

When MultiCore.java is run on a Nexus 4, I see:

Thread 1 finished in 1516ms (1267234688)
Thread 3 finished in 1494ms (1519485328)
Thread 0 finished in 1530ms (51099776)
Thread 2 finished in 1543ms (-1106614992)
All threads finished in 1550ms

Update: It's useful to watch the test with systrace. As part of answering a similar question I set up a page that shows the systrace output for this test. You can see how the threads are scheduled, and watch the other two cores spin up.

Upvotes: 3

Related Questions