并行线程执行在Oreo上运行缓慢

时间:2018-02-12 14:02:33

标签: android multithreading

我在几个月前为Android手机开发了一款游戏,在那里我使用了一种算法,在我的一些旧设备(例如Galaxy 5 mini)上花费了超过1000毫秒。因此,我根据可用处理器核心的数量将算法拆分为在几个线程中运行,将其加速到合理的处理时间(<300ms)。

在我的htc 10上的最后一周更新到Android 8.0.0之后,该设备的执行时间增加到20000奇数,用于并行执行算法。将线程数减少到一个可将执行时间缩短到不到1秒。在Android 8上运行的其他设备上的测试显示了类似的结果。

我的代码的一个基本内容是:

public class Dispatch {

private final int mTaskCount;
private final int mCores;
private static final String TAG = "asdf";
private Vector<Vertex> mVertexes = new Vector<>();
private Random mRandom;

public Dispatch(){

    mTaskCount = 30000;
    mCores = 1;//Runtime.getRuntime().availableProcessors();
    mVertexes = new Vector<>();
    mRandom = new Random();
    mRandom.setSeed(42);
    for(int i = 0; i < 30; i++){
        mVertexes.add(new Vertex(mRandom.nextFloat(), mRandom.nextFloat(), mRandom.nextFloat()));
    }
}


public void processTasks(){
    Worker[] threads = new Worker[mCores];
    Log.d(TAG, "Start time    " + System.currentTimeMillis());
    for(int i = 0; i < mCores; i++){
        threads[i] = new Worker();
        threads[i].setPart(mTaskCount / mCores * i, mTaskCount / mCores * (i+1));
        threads[i].start();
    }
    for(int i = 0; i < mCores; i++){
        try {
            threads[i].join();
        }
        catch(InterruptedException e){

        }
    }
    Log.d(TAG, "Finished time " + System.currentTimeMillis());
}


private class Worker extends Thread{
    private void setPart(int begin, int end){
        myPartBegin = begin;
        myPartEnd = end;
    }

    @Override
    public void run(){
        for(int i = myPartBegin; i < myPartEnd; i++){
            Vertex v = new Vertex(mRandom.nextFloat(), mRandom.nextFloat(), mRandom.nextFloat());
            for(int j = 0; j < mVertexes.size(); j++){
                float x = mVertexes.get(j).distance(v);
            }
        }
    }

    private int myPartBegin, myPartEnd;
}

private class Vertex {
    public float m_x;
    public float m_y;
    public float m_z;

    Vertex(float x, float y, float z) {
        m_x = x;
        m_y = y;
        m_z = z;
    }

    public float distance(Vertex v) {
        return (float) Math.sqrt((m_x - v.m_x) * (m_x - v.m_x) + (m_y - v.m_y) * (m_y - v.m_y) + (m_z - v.m_z) * (m_z - v.m_z));
    }
}
}

这是什么原因?

0 个答案:

没有答案