Androidのブート最適化(プリロード・クラスおよびリソースの最適化)

転送:https://blog.csdn.net/xxm282828/article/details/49095839

クラスとリソースセクションのためのAndroidのブートプロセスは、比較的長い時間がかかり、この部分は主に文書に関連し、最適化する必要がプリロード:

./base/core/java/com/android/internal/os/ZygoteInit.java

主要3つの施策を取ります:

1. 修改ZygoteInit.java 中预加载资源函数preload() ,  preloadClasses(); 与 preloadResources(); 并行加载。
2. 修改读取配置信息过程中GC频率。
3. 提升进程优先级

図1に示すように、リソースおよびクラスの並列ローディング:


    static void preload() {
        //
        Thread  preloadRsThread = new Thread(new Runnable(){ 
            @Override
            public void run() {
                // TODO Auto-generated method stub
            //将该资源加载放在子线程中  。加载资源文件要比加载classes文件要快,因此这里不提升子线程优先级。  
            preloadResources();
            }
 
        }) ; 
        preloadRsThread.start() ;
        preloadClasses();
        //wait preloadRes complete.
        try {
            preloadRsThread.join() ;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        //暴露什么问题。
        preloadOpenGL();
   }

2、GCの頻繁なスケジューリングを減らします:

    /**
    * Performs Zygote process initialization. Loads and initializes
     * commonly used classes.
     *
     * Most classes only cause a few hundred bytes to be allocated, but
     * a few will allocate a dozen Kbytes (in one case, 500+K).
     */
    private static void preloadClasses() {
        final VMRuntime runtime = VMRuntime.getRuntime(); 
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(
                PRELOADED_CLASSES);
        if (is == null) {
            Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
        } else {
            Log.i(TAG, "Preloading classes...");
            long startTime = SystemClock.uptimeMillis();
 
            // Drop root perms while running static initializers.
            setEffectiveGroup(UNPRIVILEGED_GID);
            setEffectiveUser(UNPRIVILEGED_UID);
 
            // Alter the target heap utilization.  With explicit GCs this
            // is not likely to have any effect.
            float defaultUtilization = runtime.getTargetHeapUtilization();
            runtime.setTargetHeapUtilization(0.8f);
 
            // Start with a clean slate.
            System.gc();
            runtime.runFinalizationSync();
            Debug.startAllocCounting(); 
            try {
                BufferedReader br
                    = new BufferedReader(new InputStreamReader(is), 256);
 
                int count = 0;
                String line;
                while ((line = br.readLine()) != null) {
                    // Skip comments and blank lines.
                    line = line.trim();
                    if (line.startsWith("#") || line.equals("")) {
                        continue;
                    } 
                    try {
                        if (false) {
                            Log.v(TAG, "Preloading " + line + "...");
                        }
                        Class.forName(line);
                        //减少GC频率,modify   begin
                        if (count%128==0&&Debug.getGlobalAllocSize() > PRELOAD_GC_THRESHOLD) {//end
                            if (false) {
                                Log.v(TAG,
                                    " GC at " + Debug.getGlobalAllocSize());
                            }
                            System.gc();
                            runtime.runFinalizationSync();
                            Debug.resetGlobalAllocSize();
                        }
                        count++;
                    } catch (ClassNotFoundException e) {
                        Log.w(TAG, "Class not found for preloading: " + line);
                    } catch (UnsatisfiedLinkError e) {
                        Log.w(TAG, "Problem preloading " + line + ": " + e);
                    } catch (Throwable t) {
                        Log.e(TAG, "Error preloading " + line + ".", t);
                        if (t instanceof Error) {
                            throw (Error) t;
                        }
                        if (t instanceof RuntimeException) {
                            throw (RuntimeException) t;
                        }
                        throw new RuntimeException(t);
                    }
                } 
                Log.i(TAG, "...preloaded " + count + " classes in "
                        + (SystemClock.uptimeMillis()-startTime) + "ms.");
            } catch (IOException e) {
                Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
            } finally {
                IoUtils.closeQuietly(is);
                // Restore default.
                runtime.setTargetHeapUtilization(defaultUtilization);
 
                // Fill in dex caches with classes, fields, and methods brought in by preloading.
                runtime.preloadDexCaches();
 
                Debug.stopAllocCounting();
 
                // Bring back root. We'll need it later.
                setEffectiveUser(ROOT_UID);
                setEffectiveGroup(ROOT_GID);
            }
        }
    }

3、プロセスの優先度を高めるために

//    ZygoteInit.java入口
    public static void main(String argv[]) {
        try { 
            //优化开机速度 begin
            /* 20150127 begin */
            //获取当前进程优先级
            int currentPriority = Process.getThreadPriority(Process.myPid()) ;
            //提升当前进程优先级。
            Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO) ;
            /* 20150127 end */            
            // Start profiling the zygote initialization.
            SamplingProfilerIntegration.start(); 
           //1.注册socket服务端
            registerZygoteSocket();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            //5.加载资源
            preload();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());
 
            // Finish profiling the zygote initialization.
            SamplingProfilerIntegration.writeZygoteSnapshot();
 
            // Do an initial gc to clean up after startup
            gc();
            
            /* 20150127 begin */
            Process.setThreadPriority(currentPriority) ;
            /* 20150127 end */
            //优化开机速度 end
            // Disable tracing so that forked processes do not inherit stale tracing tags from
            // Zygote.
            Trace.setTracingEnabled(false);
 
            // If requested, start system server directly from Zygote
            if (argv.length != 2) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }
          //2. 调用starySystemServer()方法
            if (argv[1].equals("start-system-server")) {
                startSystemServer();
            } else if (!argv[1].equals("")) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }
 
            Log.i(TAG, "Accepting command socket connections");
 
            //3.循环监听并接收客户端请求。
            runSelectLoop();
            //关闭socket
            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
          //4  《深入理解Android卷1》作者说这里比较重要
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }

4、しきい値がGCを呼び出す変更

/** when preloading, GC after allocating this many bytes 
     * 
     * 20150127 优化开机速度
     */    
    //- private static final int PRELOAD_GC_THRESHOLD = 50000;
    private static final int PRELOAD_GC_THRESHOLD = 64*1024*1024;    
    /*20150127 优化开机速度 end*/

また、Androidのシステムの起動には、リソースファイルを事前にロードされます、これらの文書は、画像やその他のリソースなど、頻繁にリソースファイルを使用するシステムのアプリケーションの多くが含まれています。したがって、唯一の低温始動高速アプリケーションを高速化することができますまた、応答速度を高めるためではなくなるように、資源の私たち自身の新しいアドオン他の部分も、事前にメモリにロードすることができる(ただし、より感度の高いシステムの起動速度の機器のために、そのような使用はお勧めしません)。

図5に示すように、プロセスの優先度に

Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // CPU時間の多くは、スレッド割り当て問題ではないときように、バックグラウンドのスレッドの優先順位を設定し、複数の並行スレッドの後に削減されます、メインスレッドの取り扱いを容易にし、次のとおりです。

int型THREAD_PRIORITY_AUDIO //スレッドの優先度標準の音楽プレーヤーを使用
int型THREAD_PRIORITY_BACKGROUND //標準のデーモン
int型THREAD_PRIORITY_DEFAULT //デフォルトのアプリケーションの優先順位
int型THREAD_PRIORITY_DISPLAY //標準表示システムの優先順位は、UIのリフレッシュ改善することが主である
THREAD_PRIORITY_FOREGROUND //標準レセプションのintをスレッドの優先
int型THREAD_PRIORITY_LESS_FAVORABLE //良好以下
のint THREAD_PRIORITY_LOWEST //有効なスレッド優先順位が最も低い
THREAD_PRIORITY_MORE_FAVORABLE //有利な上記のint
int型THREAD_PRIORITY_URGENT_AUDIO //より重要な標準のオーディオ再生優先
int型THREAD_PRIORITY_URGENT_DISPLAY //より重要な標準の表示優先度、同じことは、入力イベントに適用されます

Thread.setPriority:設定スレッドの優先順位は、JDKによって提供される方法である。
Android.os.Process.setThreadPriority:android.jarは、スレッドの優先順位方式を設定するためのDalvikのために設計され、この方法は、Androidが最優先を設定するために適している、それはDalvikする(Linux)上のより直接的な適応プロセスとの優先順位を設定することが優先事項であります

優先順位の設定のために使用した場合のプロセスの主な優先順位が比較的低い場合、優先順位の継続的なアップグレードの場合は、その後、システムの起動時にリソースのメインプロセスを共有する現在のプロセスは、システムの起動遅延に直接つながっていることに注意してください。

参考:https://my.oschina.net/kingguary/blog/1573951

         https://blog.csdn.net/xxm282828/article/details/49095839

 

おすすめ

転載: blog.csdn.net/jinron10/article/details/89315392