天天看點

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ə®] 美[ˌkɒrɪ’ɒɡrəfə®])。

oid 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中去調用。

自定義MyActivityLifeCycle實作Application.ActivityLifecycleCallbacks。

public class MyActivityLifeCycle implements Application.ActivityLifecycleCallbacks {
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private boolean mPaused = true;
    private Runnable mCheckForegroundRunnable;
    private boolean mForeground = false;
    private static MyActivityLifeCycle sInstance;
    //目前Activity的弱引用
    private WeakReference<Activity> mActivityReference;

    protected final String TAG = "#MyActivityLifeCycle";

    public static final int ACTIVITY_ON_RESUME = 0;
    public static final int ACTIVITY_ON_PAUSE = 1;

    private MyActivityLifeCycle() {
    }

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

    public Activity getCurrentActivity() {
        if (mActivityReference != null) {
            return mActivityReference.get();
        }
        return null;
    }

    public boolean isForeground() {
        return mForeground;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        mActivityReference = new WeakReference<>(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        String activityName = activity.getClass().getName();
        notifyActivityChanged(activityName, ACTIVITY_ON_RESUME);
        mPaused = false;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            FrameSkipMonitor.getInstance().setActivityName(activityName);
            FrameSkipMonitor.getInstance().OnActivityResume();
            if (!mForeground) {
                FrameSkipMonitor.getInstance().start();
            }
        }
        mForeground = true;
        if (mCheckForegroundRunnable != null) {
            mHandler.removeCallbacks(mCheckForegroundRunnable);
        }
        mActivityReference = new WeakReference<Activity>(activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {
        notifyActivityChanged(activity.getClass().getName(), ACTIVITY_ON_PAUSE);
        mPaused = true;
        if (mCheckForegroundRunnable != null) {
            mHandler.removeCallbacks(mCheckForegroundRunnable);
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
            FrameSkipMonitor.getInstance().OnActivityPause();

        mHandler.postDelayed(mCheckForegroundRunnable = new Runnable() {
            @Override
            public void run() {
                if (mPaused && mForeground) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                        FrameSkipMonitor.getInstance().report();
                    }
                    mForeground = false;
                }
            }
        }, 1000);
    }
}
           

然後在自定義的Application中調用。

public class MyApplication extends Application {
    ...
    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(MyActivityLifeCycle.getInstance());
    }
    ···
}
           

除了上述的Choreographer幀率檢測外,還有loop()列印日志等方法來對幀率進行統計監測。這裡就不一一舉例了。

正常情況下輸出的日志是:

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幀,這個卡頓使用者是能夠明顯感覺的。