1. 程式人生 > >Android效能優化第(十 一)篇---卡頓分析,正確評測流暢度

Android效能優化第(十 一)篇---卡頓分析,正確評測流暢度

一、FPS評測應用流暢度不準確

說到應用的流暢度,都會想到FPS,系統獲取FPS的原理是:手機螢幕顯示的內容是通過Android系統的SurfaceFLinger類,把當前系統裡所有程序需要顯示的資訊合成一幀,然後提交到螢幕上進行顯示,FPS就是1秒內SurfaceFLinger提交到螢幕的幀數。用FPS來評測一個應用是否真的卡頓存在兩個問題。
- 有的時候FPS很低,APP看起來卻很流暢;
- APP停止操作之後,FPS還是在一直變化,這種情況是否會影響到FPS的準確度?
有的時候FPS很低,APP看起來卻很流暢,是因為當前介面在1秒內只需要10幀的顯示需求,當然不會卡頓,此時FPS只要高於10就可以了,如果螢幕根本沒有繪製需求,那FPS的值就是0。

Android效能優化第(四)篇—Android渲染機制說過,Android系統每隔16ms發出VSYNC訊號,觸發對UI的渲染,16ms沒完成繪製就會卡頓。VSync機制就像是一臺轉速固定的發動機(60轉/s)。每一轉會帶動著去做一些UI相關的事情,但不是每一轉都會有工作去做(就像有時在空擋,有時在D檔)。有時候因為各種阻力某一圈工作量比較重超過了16.6ms,那麼這臺發動機這秒內就不是60轉了,當然也有可能被其他因素影響,比如給油不足(主執行緒裡乾的活太多)等等,就會出現轉速降低的狀況。我們把這個轉速叫做流暢度。當流暢度越小的時候說明當前程式越卡頓。

二、Choreographer幀率檢測原理

我們有時候會看到這樣的log,系統幫助我們打印出了跳幀數。

02-07 19:47:04.333 17601-17604/zhangwan.wj.com.choreographertest D/dalvikvm: GC_CONCURRENT freed 143K, 3% free 9105K/9384K, paused 2ms+0ms, total 6ms
02-07 19:47:04.337 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 60 frames!  The application may be doing too much work on
its main thread. 02-07 19:47:11.685 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 85 frames! The application may be doing too much work on its main thread. 02-07 19:47:12.545 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread. 02-07 19:47:14.893 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread. 02-07 19:47:23.049 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread. 02-07 19:47:23.929 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread. 02-07 19:47:24.961 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 61 frames! The application may be doing too much work on its main thread. 02-07 19:47:25.817 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread. 02-07 19:47:26.433 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.

這個log就出自於Choreographer中(英[ˌkɒrɪ’ɒɡrəfə(r)] 美[ˌkɒrɪ’ɒɡrəfə(r)])。

void doFrame(long frameTimeNanos, int frame) {
        final long startNanos;
        synchronized (mLock) {
            if (!mFrameScheduled) {
                return; // no work to do
            }

            if (DEBUG_JANK && mDebugPrintNextFrameTimeDelta) {
                mDebugPrintNextFrameTimeDelta = false;
                Log.d(TAG, "Frame time delta: "
                        + ((frameTimeNanos - mLastFrameTimeNanos) * 0.000001f) + " ms");
            }

            long intendedFrameTimeNanos = frameTimeNanos;
            startNanos = System.nanoTime();
            final long jitterNanos = startNanos - frameTimeNanos;
            if (jitterNanos >= mFrameIntervalNanos) {
                final long skippedFrames = jitterNanos / mFrameIntervalNanos;
                if (skippedFrames >= SKIPPED_FRAME_WARNING_LIMIT) {
                    Log.i(TAG, "Skipped " + skippedFrames + " frames!  "
                            + "The application may be doing too much work on its main thread.");
                }
                final long lastFrameOffset = jitterNanos % mFrameIntervalNanos;
                if (DEBUG_JANK) {
                    Log.d(TAG, "Missed vsync by " + (jitterNanos * 0.000001f) + " ms "
                            + "which is more than the frame interval of "
                            + (mFrameIntervalNanos * 0.000001f) + " ms!  "
                            + "Skipping " + skippedFrames + " frames and setting frame "
                            + "time to " + (lastFrameOffset * 0.000001f) + " ms in the past.");
                }
                frameTimeNanos = startNanos - lastFrameOffset;
            }
        }

    }

其中SKIPPED_FRAME_WARNING_LIMIT是Choreographer的成員變數。

  // Set a limit to warn about skipped frames.
  // Skipped frames imply jank.
  private static final int SKIPPED_FRAME_WARNING_LIMIT =SystemProperties.getInt( "debug.choreographer.skipwarning", 30);

也就是當跳幀數大於設定的SKIPPED_FRAME_WARNING_LIMIT 值時會在當前程序輸出這個log。由於 SKIPPED_FRAME_WARNING_LIMIT 的值預設為 30,所以上面的log並不是經常看到,如果我們用反射的方法把SKIPPED_FRAME_WARNING_LIMIT的值設定成1,這樣可以保證只要有丟幀,就會有上面的log輸出來。

static {
        try {
            Field field = Choreographer.class.getDeclaredField("SKIPPED_FRAME_WARNING_LIMIT");
            field.setAccessible(true);
            field.set(Choreographer.class,1);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

注意,這個方案是 API 16 以上才支援。Choreographer就是一個訊息處理器,根據vsync 訊號 來計算frame,而計算frame的方式就是處理三種回撥,包括事件回撥、動畫回撥、繪製回撥。這三種事件在訊息輸入、加入動畫、準備繪圖layout 等動作時均會發給Choreographer。一句話,我們只要捕獲這個log提取出skippedFrames 就可以知道介面是否卡頓。

三、如何檢測

採用上面的方式就可以在App內部觀測當前App的流暢度了。並且在丟幀的地方列印,就可以知道丟幀的大概原因,大概位置,定位程式碼問題。

在Choreographer中有個回撥介面,FrameCallback。

public interface FrameCallback {  
  //當新的一幀被繪製的時候被呼叫。  
   public void doFrame(long frameTimeNanos);
}

根據上面的程式碼,重寫doFrame方法,所以照葫蘆畫瓢,自定義FrameCallback。我們可以在每一幀被渲染的時候記錄下它開始渲染的時間,這樣在下一幀被處理時,判斷上一幀在渲染過程中是否出現掉幀。

public class SMFrameCallback implements Choreographer.FrameCallback {

    public static  SMFrameCallback sInstance;

    private String TAG="SMFrameCallback";

    public static final float deviceRefreshRateMs=16.6f;

    public static  long lastFrameTimeNanos=0;//納秒為單位

    public static  long currentFrameTimeNanos=0;

    public void start() {
        Choreographer.getInstance().postFrameCallback(SMFrameCallback.getInstance());
    }

    public static SMFrameCallback getInstance() {
        if (sInstance == null) {
            sInstance = new SMFrameCallback();
        }
        return sInstance;
    }

    @Override
    public void doFrame(long frameTimeNanos) {
        if(lastFrameTimeNanos==0){
            lastFrameTimeNanos=frameTimeNanos;
            Choreographer.getInstance().postFrameCallback(this);
            return;
        }
        currentFrameTimeNanos=frameTimeNanos;
        float value=(currentFrameTimeNanos-lastFrameTimeNanos)/1000000.0f;

        final int skipFrameCount = skipFrameCount(lastFrameTimeNanos, currentFrameTimeNanos, deviceRefreshRateMs);
        Log.e(TAG,"兩次繪製時間間隔value="+value+"  frameTimeNanos="+frameTimeNanos+"  currentFrameTimeNanos="+currentFrameTimeNanos+"  skipFrameCount="+skipFrameCount+"");
        lastFrameTimeNanos=currentFrameTimeNanos;
        Choreographer.getInstance().postFrameCallback(this);
    }


    /**
     *
     *計算跳過多少幀
     * @param start
     * @param end
     * @param devicefreshRate
     * @return
     */
    private  int skipFrameCount(long start,long end,float devicefreshRate){
        int count =0;
        long diffNs=end-start;
        long diffMs = Math.round(diffNs / 1000000.0f);
        long dev=Math.round(devicefreshRate);
        if(diffMs>dev){
            long skipCount=diffMs/dev;
            count=(int)skipCount;
        }
        return  count;
    }
}

在需要檢測的Activity中呼叫 SMFrameCallback.getInstance().start()即可。一般優化一下,可以在BaseActivity去呼叫或者Activitylifecyclecallbacks中去呼叫.
正常情況下輸出的日誌是:

02-07 20:18:52.605 6683-6683/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=6996166386820  currentFrameTimeNanos=6996166386820  skipFrameCount=0
02-07 20:18:52.621 6683-6683/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=6996183053486  currentFrameTimeNanos=6996183053486  skipFrameCount=0
02-07 20:18:52.637 6683-6683/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=6996199720152  currentFrameTimeNanos=6996199720152  skipFrameCount=0
02-07 20:18:52.657 6683-6683/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=6996216386818  currentFrameTimeNanos=6996216386818  skipFrameCount=0
02-07 20:18:52.673 6683-6683/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=6996233053484  currentFrameTimeNanos=6996233053484  skipFrameCount=0
02-07 20:18:52.689 6683-6683/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=6996249720150  currentFrameTimeNanos=6996249720150  skipFrameCount=0

有跳幀的時候輸出的日誌是

02-07 20:21:53.909 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=7177466379568  currentFrameTimeNanos=7177466379568  skipFrameCount=0
02-07 20:21:53.925 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=7177483046234  currentFrameTimeNanos=7177483046234  skipFrameCount=0
02-07 20:21:54.133 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=200.0  frameTimeNanos=7177683046226  currentFrameTimeNanos=7177683046226  skipFrameCount=11
02-07 20:21:54.745 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=616.6666  frameTimeNanos=7178299712868  currentFrameTimeNanos=7178299712868  skipFrameCount=36
02-07 20:21:54.757 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=7178316379534  currentFrameTimeNanos=7178316379534  skipFrameCount=0
02-07 20:21:54.773 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=7178333046200  currentFrameTimeNanos=7178333046200  skipFrameCount=0
02-07 20:21:54.789 9530-9530/zhangwan.wj.com.choreographertest E/SMFrameCallback: 兩次繪製時間間隔value=16.666666  frameTimeNanos=7178349712866  currentFrameTimeNanos=7178349712866  skipFrameCount=0

看到兩次繪製的時間間隔相差616.6666毫秒,跳過了36幀,這個卡頓使用者是能夠明顯感知的。

Please accept mybest wishes for your happiness and success !