美文网首页工具安卓开发经验Android技术研究
Android性能优化第(十 一)篇---卡顿分析,正确评测流畅

Android性能优化第(十 一)篇---卡顿分析,正确评测流畅

作者: LooperJing | 来源:发表于2017-02-07 20:29 被阅读6444次

转载请注明文章出处LooperJing

一、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 !

相关文章

  • Android性能优化第(十 一)篇---卡顿分析,正确评测流畅

    转载请注明文章出处LooperJing! 一、FPS评测应用流畅度不准确 说到应用的流畅度,都会想到FPS,系统获...

  • Android开发页面帧率优化有感

    Android APP 优化工具分析Android App优化之消除卡顿Android性能优化:卡顿优化Andro...

  • Android性能优化 - 消除卡顿

    性能优化系列阅读 Android性能优化 性能优化 - 消除卡顿 性能优化 - 内存优化 性能分析工具 - Tra...

  • Android性能优化 - 内存优化

    性能优化系列阅读 Android性能优化 性能优化 - 消除卡顿 性能优化- 内存优化 性能分析工具 - Trac...

  • Android性能优化

    Android的性能优化,主要是从以下几个方面进行优化的: 稳定(内存溢出、崩溃) 流畅(卡顿) 耗损(耗电、流量...

  • 无标题文章

    APP性能优化 UI卡顿优化 View的绘制原理 UI卡顿原理分析 UI卡顿检测分析 BlockCanary原理分...

  • Android优化文章精选

    Android性能优化典范 Android性能优化典范 - 第1季Android性能优化之渲染篇Android性能...

  • 性能优化题

    android性能优化 四个方面总结如下:稳定(内存溢出、崩溃)流畅(卡顿)耗损(耗电、流量)安装包(APK瘦身)...

  • 性能优化总结

    性能优化方向 流畅(启动速度、卡顿) 稳定(内存泄漏、崩溃) 功耗(耗电、网络) 安装包(包体积) 一、 流畅 卡...

  • Android性能优化

    Android性能优化 Android 性能优化的方法 性能问题一般分为3类 UI卡顿 内存问题 耗电问题 布局优...

网友评论

  • 小红军storm:根据打印的log,怎么判断是哪里的代码卡顿了?
  • d13c2e674156:有个开源库 集成到apk中可用 分享下
    https://github.com/wasabeef/Takt
  • Dinos:楼主,我又过来了,突然发现后面的没写。=_= ....
    LooperJing:@Dinos :smiley: 写一篇要花掉很多时间啊,我尽量补上
  • 5ea4beb37efa:前辈,您好我是小米工程师 我最近也研究这个编舞者 方便加下微信交流吗 shaoxy1992 备注写下简书LooperJing 嘿嘿方便备注
    5ea4beb37efa:@LooperJing :clap: :+1: 欢迎大牛啊~
    LooperJing: @邵翔宇 即将成为同事了

本文标题:Android性能优化第(十 一)篇---卡顿分析,正确评测流畅

本文链接:https://www.haomeiwen.com/subject/mhipittx.html