本文介绍了我怎样才能确保我的线程/进程在不同内核上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想衡量我的code的性能改进,当我运行与单核Android设备多核设备(如S3)在我的多线程的Andr​​oid应用程序。衡量业绩,我按顺序运行的任务与并行。我实现了普通的Java线程,这似乎并没有发挥作用。因此,我试过AsynchTask,但我只得到了性能改进一点点。

你能不能让我知道我可以写code,使确保每个我的任务/线程正在在不同内核上运行,而不是单一的一个?如果这是不可能的,我怎么能最大限度地利用多个核心的我的应用程序?

这里的code为执行任务的活动的onCreate方法。

 保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_local_executor);    multiplicationTask T1 =新multiplicationTask();
    t1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);    multiplicationTask T2 =新multiplicationTask();
    t2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);    multiplicationTask T3 =新multiplicationTask();
    t3.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);    multiplicationTask T4 =新multiplicationTask();
    t4.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);}

下面是从onCreate方法运行AsynchTask

 类multiplicationTask扩展的AsyncTask<整数,整数,字符串> {    在preExecute保护无效()
    {
        Log.v(的println,执行任务);
    }    @覆盖
    保护字符串doInBackground(整数... PARAMS){
     //做大量的浮点运算独立于任何事情任何
    }
    保护无效onPostExecute(字符串结果){
        Log.v(的println,完成任务:+ resulting_time);
    }}


解决方案

That will be handled automatically by the JVM / android. If you don't see any performance gains, the likeliest reasons are:

  • the tasks are not parallelisable (for example you calculate two results but the second depends on the first so they run sequentially)
  • the tasks are no CPU-bound (i.e. if you read a huge file, the bottleneck is the speed of you storage, not the CPU, and adding threads won't help)
  • you don't start enough threads / you start too many threads

I suggest you show the code that create and start the threads as well as give an idea of what the tasks do if you need a more specific answer.

EDIT

Note that AsyncTask's primary use is to run short background tasks that interact with the UI. In your case, a plain executor would probably be better. The basic syntax to create one would be:

private static final int N_CPUS = Runtime.getRuntime().availableProcessors() + 1;
private final ExecutorService executor = Executors.newFixedThreadPool(N_CPUS);

And to use it:

executor.submit(new Runnable() {
    public void run() {
        Log.v("PrintLN", "Executing Task");
        //your code here
        Log.v("PrintLN", "Done Task: " + resulting_time);
    }
});

And don't forget to shutdown the executor when you are done.

Now the performance improvement will vary on a number of factors. In your case, if tasks are too short lived, the context switching overhead (when the CPU activates one thread or another) can be large enough that the benefits of multiple threads can be offset.

Another possible bottleneck is synchronization: if you exchange data across threads continuously this will cause a lot of overhead too.

这篇关于我怎样才能确保我的线程/进程在不同内核上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:00