App Launch Time Measurement

本文介绍了两种测量Android应用启动时间的方法:displaytime和fullydrawntime,并详细解释了这两种方法的区别及其实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文记录下分析应用启动时间的总结。

关于应用启动时间测量的分析已经有不少不错的文章做了总结,下面是比较好的几篇:
1.Android性能优化典范-第6季
2.测量Activity 的启动时间
3.Activity到底是什么时候显示到屏幕上的呢

上面的每篇都各有特色,我这篇也只是在他们的分析上记录下自己学习和研究过程的总结。

1.查看display time

从Android KitKat版本开始,Logcat中会输出从程序启动到Activity显示到屏幕上所花费的时间,这个时间包含了进程启动的时间,比较适合测量程序的启动时间。

I ActivityManager: Displayed com.meizu.flyme.applaunch/.MainActivity: +379ms
//厂商定制过的OS可能会有些不同,例如FlymeOS中的输出
I ActivityManager: [AppLaunch] Displayed Displayed com.meizu.flyme.applaunch/.MainActivity: +480ms

上面信息的打印来自ActivityRecord类的reportLaunchTimeLocked方法,它的实现如下所示,整个过程和下面的fully drawn time类似,我们在下面会介绍它的详细实现过程。

img

除了看Logcat之外,我们还有其他的方式来查看上面的时间,例如使用am start的方式查看TotalTime

$ adb shell am start -W com.meizu.flyme.applaunch/.MainActivity
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.meizu.flyme.applaunch/.MainActivity }
Status: ok
Activity: com.meizu.flyme.applaunch/.MainActivity
ThisTime: 479
TotalTime: 479
WaitTime: 499
Complete

或者查看EventLog的方法来查看am_activity_launch_time

$adb shell logcat -b events
... I am_activity_launch_time: [0,200792421,com.meizu.flyme.applaunch/.MainActivity,478,478]

2.查看fully drawn time

通常应用启动的时候都会以异步加载的方式来加快应用的启动速度,但是上面的display time是不包含异步加载所耗费的时间,所以为了准确衡量应用的启动时间,我们可以在异步加载完毕之后调用Activity.reportFullyDrawn()方法来告诉系统加载完成,以便获取整个应用启动的耗时。

查看方式和输出结果类似上面的查看display time的过程

//Logcat中的输出
I ActivityManager: Fully drawn com.meizu.flyme.applaunch/.MainActivity: +2s319ms
//EventLog中的输出
... I am_activity_fully_drawn_time: [0,200792421,com.meizu.flyme.applaunch/.MainActivity,478,478]

下面是Activity.reportFullyDrawn()方法的实现,从注释来看,这个方法主要是用来帮助我们测量应用的启动时间,因为系统最多只能确定应用的window第一次绘制和显示的时间点,不能确定应用真正加载完成处于可以使用状态的时间点,所以需要开发者来显式调用这个方法以通知系统应用已经启动完毕可以使用了。

/**
 * Report to the system that your app is now fully drawn, purely for diagnostic
 * purposes (calling it does not impact the visible behavior of the activity).
 * This is only used to help instrument application launch times, so that the
 * app can report when it is fully in a usable state; without this, the only thing
 * the system itself can determine is the point at which the activity's window
 * is <em>first</em> drawn and displayed.  To participate in app launch time
 * measurement, you should always call this method after first launch (when
 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
 * entirely drawn your UI and populated with all of the significant data.  You
 * can safely call this method any time after first launch as well, in which case
 * it will simply be ignored.
 */
public void reportFullyDrawn() {
    if (mDoReportFullyDrawn) {
        mDoReportFullyDrawn = false;
        try {
            ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
        } catch (RemoteException e) {
        }
    }
}

其中的ActivityManagerNativereportActivityFullyDrawn方法会经过Binder调用到AMS的reportActivityFullyDrawn方法,最终会调用到ActivityRecordreportFullyDrawnLocked方法,内容与reportLaunchTimeLocked方法类似。

public void reportFullyDrawnLocked() {
    final long curTime = SystemClock.uptimeMillis();
    if (displayStartTime != 0) {
        reportLaunchTimeLocked(curTime);
    }
    final ActivityStack stack = task.stack;
    if (fullyDrawnStartTime != 0 && stack != null) {
        final long thisTime = curTime - fullyDrawnStartTime;
        final long totalTime = stack.mFullyDrawnStartTime != 0
                ? (curTime - stack.mFullyDrawnStartTime) : thisTime;
        if (SHOW_ACTIVITY_START_TIME) {
            Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
            EventLog.writeEvent(EventLogTags.AM_ACTIVITY_FULLY_DRAWN_TIME,
                    userId, System.identityHashCode(this), shortComponentName,
                    thisTime, totalTime);//EventLog中的输出
            StringBuilder sb = service.mStringBuilder;
            sb.setLength(0);
            sb.append("Fully drawn ");
            sb.append(shortComponentName);
            sb.append(": ");
            TimeUtils.formatDuration(thisTime, sb);
            if (thisTime != totalTime) {
                sb.append(" (total ");
                TimeUtils.formatDuration(totalTime, sb);
                sb.append(")");
            }
            Log.i(TAG, sb.toString());//Logcat中的输出
        }
        if (totalTime > 0) {
            //service.mUsageStatsService.noteFullyDrawnTime(realActivity, (int) totalTime);
        }
        stack.mFullyDrawnStartTime = 0;
    }
    fullyDrawnStartTime = 0;
}

上面代码中有个起始时间(fullyDrawnStartTime),它是在哪里设置的呢?它是在ActivityStacksetLaunchTime方法中设置的。
注:下面代码中的Trace.asyncTraceBeginTrace.asyncTraceEnd实际上会调用到系统中atraceasync_startasync_stop(可以通过adb shell atrace -h查看到这两个命令的选项)。

void setLaunchTime(ActivityRecord r) {
    if (r.displayStartTime == 0) {
        r.fullyDrawnStartTime = r.displayStartTime = SystemClock.uptimeMillis();
        if (mLaunchStartTime == 0) {
            startLaunchTraces(r.packageName);
            mLaunchStartTime = mFullyDrawnStartTime = r.displayStartTime;
        }
    } else if (mLaunchStartTime == 0) {
        startLaunchTraces(r.packageName);
        mLaunchStartTime = mFullyDrawnStartTime = SystemClock.uptimeMillis();
    }
}

private void startLaunchTraces(String packageName) {
    if (mFullyDrawnStartTime != 0)  {
        Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
    }
    Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching: " + packageName, 0);
    Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
}

private void stopFullyDrawnTraceIfNeeded() {
    if (mFullyDrawnStartTime != 0 && mLaunchStartTime == 0) {
        Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
        mFullyDrawnStartTime = 0;
    }
}

setLaunchTime方法是何时调用的呢?它是在ActivityStackSupervisor.startSpecificActivityLocked方法中调用的!
startSpecificActivityLocked方法中会判断应用进程是否启动了,如果没有启动就调用startProcessLocked方法来启动进程,内部会调用Process类的start方法来启动新进程;否则调用realStartActivityLocked方法继续执行,这个方法会调用scheduleLaunchActivity方法,内部将会调用ActivityonCreate方法,开始Activity的生命周期。

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);

    r.task.stack.setLaunchTime(r);//在这里设置launch start time

    if (app != null && app.thread != null) {
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android".equals(r.info.packageName)) {
                // Don't add this if it is a platform component that is marked
                // to run in multiple processes, because this is actually
                // part of the framework so doesn't make sense to track as a
                // separate apk in the process.
                app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats);
            }
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e);
        }

        // If a dead object exception was thrown -- fall through to restart the application.
    }

    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}
. ├── cliff_distance_measurement │ ├── CMakeLists.txt │ ├── include │ │ └── cliff_distance_measurement │ ├── package.xml │ └── src │ ├── core │ ├── ir_ranging.cpp │ └── platform ├── robot_cartographer │ ├── config │ │ └── fishbot_2d.lua │ ├── map │ │ ├── fishbot_map.pgm │ │ └── fishbot_map.yaml │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_cartographer │ ├── robot_cartographer │ │ ├── __init__.py │ │ └── robot_cartographer.py │ ├── rviz │ ├── setup.cfg │ └── setup.py ├── robot_control_service │ ├── bash │ │ └── pwm_control_setup.sh │ ├── CMakeLists.txt │ ├── config │ │ └── control_params.yaml │ ├── include │ │ └── robot_control_service │ ├── package.xml │ ├── readme.md │ └── src │ ├── control_client_camera.cpp │ ├── control_client_cliff.cpp │ ├── control_client_ir.cpp │ ├── control_client_ir_four.cpp │ ├── control_client_master.cpp │ ├── control_client_ros.cpp │ ├── control_client_ultrasonic.cpp │ ├── control_service.cpp │ ├── DirectMotorControl.cpp │ ├── PIDControl.cpp │ ├── publisher_control_view.cpp │ └── publisher_human_realized.cpp ├── robot_control_view │ ├── config │ │ └── icare_robot.rviz │ ├── __init__.py │ ├── launch │ │ └── start_init_view.launch.py │ ├── package.xml │ ├── resource │ │ └── robot_control_view │ ├── robot_control_view │ │ ├── app │ │ ├── blood_oxygen_pulse │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── robot_automatic_cruise_server.py │ │ ├── robot_automatic_recharge_server.py │ │ ├── robot_automatic_slam_server.py │ │ ├── robot_blood_oxygen_pulse.py │ │ ├── robot_city_locator_node.py │ │ ├── robot_control_policy_server.py │ │ ├── robot_local_websocket.py │ │ ├── robot_log_clear_node.py │ │ ├── robot_main_back_server.py │ │ ├── robot_network_publisher.py │ │ ├── robot_network_server.py │ │ ├── robot_odom_publisher.py │ │ ├── robot_speech_server.py │ │ ├── robot_system_info_node.py │ │ ├── robot_ultrasonic_policy_node.py │ │ ├── robot_view_manager_node.py │ │ ├── robot_websockets_client.py │ │ ├── robot_websockets_server.py │ │ ├── robot_wifi_server_node.py │ │ ├── start_account_view.py │ │ ├── start_bluetooth_view.py │ │ ├── start_chat_view.py │ │ ├── start_clock_view.py │ │ ├── start_feedback_view.py │ │ ├── start_health_view.py │ │ ├── start_init_view.py │ │ ├── start_lifecycle_view.py │ │ ├── start_main_view.py │ │ ├── start_member_view.py │ │ ├── start_movie_view.py │ │ ├── start_music_view.py │ │ ├── start_radio_view.py │ │ ├── start_schedule_view.py │ │ ├── start_setting_view.py │ │ ├── start_test_view.py │ │ ├── start_view_manager.py │ │ ├── start_weather_view.py │ │ └── start_wifi_view.py │ ├── setup.cfg │ ├── setup.py │ ├── test │ │ ├── my_test.py │ │ ├── test_copyright.py │ │ ├── test_flake8.py │ │ └── test_pep257.py │ └── urdf │ ├── first_robot.urdf.xacro │ ├── fishbot.urdf │ ├── fishbot.urdf.xacro │ ├── fist_robot.urdf │ ├── icare_robot.urdf │ ├── icare_robot.urdf.xacro │ ├── ramand.md │ └── xacro_template.xacro ├── robot_costmap_filters │ ├── CMakeLists.txt │ ├── include │ │ └── robot_costmap_filters │ ├── launch │ │ ├── start_costmap_filter_info_keepout.launch.py │ │ ├── start_costmap_filter_info.launch.py │ │ └── start_costmap_filter_info_speedlimit.launch.py │ ├── package.xml │ ├── params │ │ ├── filter_info.yaml │ │ ├── filter_masks.yaml │ │ ├── keepout_mask.pgm │ │ ├── keepout_mask.yaml │ │ ├── keepout_params.yaml │ │ ├── speedlimit_params.yaml │ │ ├── speed_mask.pgm │ │ └── speed_mask.yaml │ ├── readme.md │ └── src ├── robot_description │ ├── launch │ │ └── gazebo.launch.py │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_description │ ├── robot_description │ │ └── __init__.py │ ├── rviz │ │ └── urdf_config.rviz │ ├── setup.cfg │ ├── setup.py │ ├── urdf │ │ ├── fishbot_gazebo.urdf │ │ ├── fishbot_v0.0.urdf │ │ ├── fishbot_v1.0.0.urdf │ │ ├── test.urdf │ │ └── three_wheeled_car_model.urdf │ └── worlds │ └── empty_world.world ├── robot_interfaces │ ├── CMakeLists.txt │ ├── include │ │ └── robot_interfaces │ ├── msg │ │ ├── AlarmClockMsg.msg │ │ ├── CameraMark.msg │ │ ├── DualRange.msg │ │ ├── HuoerSpeed.msg │ │ ├── IrSensorArray.msg │ │ ├── IrSignal.msg │ │ ├── NavigatorResult.msg │ │ ├── NavigatorStatus.msg │ │ ├── NetworkDataMsg.msg │ │ ├── PoseData.msg │ │ ├── RobotSpeed.msg │ │ ├── SensorStatus.msg │ │ ├── TodayWeather.msg │ │ └── WifiDataMsg.msg │ ├── package.xml │ ├── readme.md │ ├── src │ └── srv │ ├── LightingControl.srv │ ├── MotorControl.srv │ ├── NewMotorControl.srv │ ├── SetGoal.srv │ ├── StringPair.srv │ ├── String.srv │ └── VoicePlayer.srv ├── robot_launch │ ├── config │ │ └── odom_imu_ekf.yaml │ ├── launch │ │ ├── start_all_base_sensor.launch.py │ │ ├── start_cartographer.launch.py │ │ ├── start_control_service.launch.py │ │ ├── start_navigation.launch.py │ │ ├── start_navigation_service.launch.py │ │ ├── start_navigation_speed_mask.launch.py │ │ ├── start_navigation_with_speed_and_keepout.launch.py │ │ ├── start_ros2.launch.py │ │ ├── test_camera_2.launch.py │ │ ├── test_camera.launch.py │ │ ├── test_car_model.launch.py │ │ ├── test_cliff.launch.py │ │ ├── test_ir.launch.py │ │ ├── test_self_checking.launch.py │ │ ├── test_video_multiplesing.launch.py │ │ └── test_visualization.launch.py │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_launch │ ├── robot_launch │ │ └── __init__.py │ ├── setup.cfg │ └── setup.py ├── robot_navigation │ ├── config │ │ ├── nav2_filter.yaml │ │ ├── nav2_params.yaml │ │ └── nav2_speed_filter.yaml │ ├── maps │ │ ├── fishbot_map.pgm │ │ └── fishbot_map.yaml │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_navigation │ ├── robot_navigation │ │ ├── __init__.py │ │ └── robot_navigation.py │ ├── setup.cfg │ └── setup.py ├── robot_navigation2_service │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_navigation2_service │ ├── robot_navigation2_service │ │ ├── camera_follower_client.py │ │ ├── go_to_pose_service.py │ │ ├── __init__.py │ │ ├── leave_no_parking_zone_client_test_2.py │ │ ├── pose_init.py │ │ ├── real_time_point_client.py │ │ ├── recharge_point_client.py │ │ ├── repub_speed_filter_mask.py │ │ └── save_pose.py │ ├── setup.cfg │ └── setup.py ├── robot_sensor │ ├── bash │ │ └── isr_brushless.sh │ ├── CMakeLists.txt │ ├── config │ │ └── sensor_params.yaml │ ├── include │ │ └── robot_sensor │ ├── package.xml │ ├── readme.md │ └── src │ ├── robot_battery_state_publisher.cpp │ ├── robot_battery_voltage_publisher.cpp │ ├── robot_charging_status_publisher.cpp │ ├── robot_cliff_distance_publisher.cpp │ ├── robot_encode_speed_publisher.cpp │ ├── robot_imu_publisher.cpp │ ├── robot_ir_four_signal_publisher.cpp │ ├── robot_ir_signal_publisher.cpp │ ├── robot_keyboard_control_publisher.cpp │ ├── robot_lighting_control_server.cpp │ ├── robot_map_publisher.cpp │ ├── robot_odom_publisher.cpp │ ├── robot_smoke_alarm_publisher.cpp │ ├── robot_ultrasonic_publisher.cpp │ └── robot_wireless_alarm_publisher.cpp ├── robot_sensor_self_check │ ├── check_report │ │ ├── sensor_diagnostic_report_20250226_144435.json │ │ ├── sensor_diagnostic_report_20250226_144435.txt │ │ ├── sensor_diagnostic_report_20250226_144850.json │ │ ├── sensor_diagnostic_report_20250226_144850.txt │ │ ├── sensor_diagnostic_report_20250226_144927.json │ │ ├── sensor_diagnostic_report_20250226_144927.txt │ │ ├── sensor_diagnostic_report_20250226_144958.json │ │ └── sensor_diagnostic_report_20250226_144958.txt │ ├── config │ │ └── sensors_config.yaml │ ├── package.xml │ ├── resource │ │ └── robot_sensor_self_check │ ├── robot_sensor_self_check │ │ ├── __init__.py │ │ ├── robot_sensor_self_check.py │ │ └── test_topic.py │ ├── setup.cfg │ ├── setup.py │ └── test │ ├── test_copyright.py │ ├── test_flake8.py │ └── test_pep257.py ├── robot_visual_identity │ ├── cfg │ │ ├── nanotrack.yaml │ │ ├── rknnconfig.yaml │ │ └── stgcnpose.yaml │ ├── face_feature │ │ ├── mss_face_encoding.npy │ │ ├── wd_face_encoding.npy │ │ └── yls_face_encoding.npy │ ├── package.xml │ ├── resource │ │ ├── robot_visual_identity │ │ └── ros_rknn_infer │ ├── rknn_model │ │ ├── blood_detect.rknn │ │ ├── blood-seg-last-cbam.rknn │ │ ├── face_detect.rknn │ │ ├── face_emotion.rknn │ │ ├── face_keypoint.rknn │ │ ├── face_verify.rknn │ │ ├── head_detect.rknn │ │ ├── nanotrack_backbone127.rknn │ │ ├── nanotrack_backbone255.rknn │ │ ├── nanotrack_head.rknn │ │ ├── people_detect.rknn │ │ ├── stgcn_pose.rknn │ │ ├── yolo_kpt.rknn │ │ └── yolov8s-pose.rknn │ ├── robot_visual_identity │ │ ├── 人体跟随与避障控制系统文档.md │ │ ├── __init__.py │ │ ├── rknn_infer │ │ ├── robot_behavior_recognition.py │ │ ├── robot_emotion_recognition.py │ │ ├── robot_people_rgb_follow.py │ │ ├── robot_people_scan_follow.py │ │ └── robot_people_track.py │ ├── setup.cfg │ ├── setup.py │ └── test │ ├── test_copyright.py │ ├── test_flake8.py │ └── test_pep257.py ├── video_multiplexing │ ├── bash │ │ ├── test_config.linphonerc │ │ ├── test_video_stream.sh │ │ └── video_stream.pcap │ ├── COLCON_IGNORE │ ├── package.xml │ ├── resource │ │ └── video_multiplexing │ ├── setup.cfg │ ├── setup.py │ ├── test │ │ ├── test_copyright.py │ │ ├── test_flake8.py │ │ └── test_pep257.py │ └── video_multiplexing │ ├── __init__.py │ ├── __pycache__ │ ├── rtp_utils.py │ ├── video_freeswitch.py │ ├── video_linphone_bridge.py │ ├── video_publisher.py │ └── video_test_freeswitch.py └── ydlidar_ros2_driver-humble ├── CMakeLists.txt ├── config │ └── ydlidar.rviz ├── details.md ├── images │ ├── cmake_error.png │ ├── EAI.png │ ├── finished.png │ ├── rviz.png │ ├── view.png │ └── YDLidar.jpg ├── launch │ ├── ydlidar_launch.py │ ├── ydlidar_launch_view.py │ └── ydlidar.py ├── LICENSE.txt ├── package.xml ├── params │ └── TminiPro.yaml ├── README.md ├── src │ ├── ydlidar_ros2_driver_client.cpp │ └── ydlidar_ros2_driver_node.cpp └── startup └── initenv.sh 93 directories, 299 files 我的机器人ros2系统是有显示和主控页面的居家服务型移动机器人,用户点击下载更新就开始执行更新流程,整个系统更新功能应该怎么设计,在开发者应该编写哪些代码和做哪些准备,如何设计流程
07-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值