如何查看启动耗时
- 在AndroidStudio的Logcat窗口输入
Displayed
关键字过滤,如下所示:
1
| 2020-01-03 10:53:02.804 1402-1479/? I/ActivityManager: Displayed com.markzl.android.simpleapplication/.HelloActivity: +509ms
|
- 通过指令
adb shell am start -W packagename/LaunchActivityName
执行:
1 2 3 4 5 6 7 8 9
| zhoudeMacBook-Pro:SimpleApplication markzl$ adb shell am start -W com.markzl.android.simpleapplication/.HelloActivity Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.markzl.android.simpleapplication/.HelloActivity } Status: ok Activity: com.markzl.android.simpleapplication/.HelloActivity ThisTime: 509 TotalTime: 509 WaitTime: 530 Complete zhoudeMacBook-Pr
|
ThisTime
:一般和TotalTime时间一样。除非在应用启动时开了一个透明的Activity预先处理一些事再显示出主Activity,这样将比TotalTime小。
TotalTime
:应用的启动时间。包含创建进程+Application初始化+Activity初始化到界面显示。
WaitTime
:一般比TotalTime大点,包含系统影响的耗时。
如何计算方法耗时
使用aspect面向切面,计算方法耗时
定义切点:
1 2 3 4 5
| @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface BehaviorTrace { String value(); }
|
定义切面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @Aspect public class BehaviorAspect {
private static final String POINTCUT_METHOD = "execution(@com.markzl.android.aspectj.BehaviorTrace * *(..))"; private static final String POINTCUT_CONSTRUCTOR = "execution(@com.markzl.android.aspectj.BehaviorTrace *.new(..))";
@Pointcut(POINTCUT_METHOD) public void methodAnnotationWithBehaviorTrace() { }
@Pointcut(POINTCUT_CONSTRUCTOR) public void constructorAnnotationWithBehaviorTrace() { } @Around("methodAnnotationWithBehaviorTrace()||constructorAnnotationWithBehaviorTrace()") public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName();
BehaviorTrace behaviorTrace = methodSignature.getMethod().getAnnotation(BehaviorTrace.class); String value = behaviorTrace.value();
StopWatch stopWatch = new StopWatch(); stopWatch.start(); Object result = joinPoint.proceed(); stopWatch.stop(); Log.d(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis())); Log.d(className, value); return result; } }
|
AOP 特性无侵入性且修改方便。
启动速度分析工具 —— TraceView
使用方式1:
在方法执行开始处添加:
1
| Debug.startMethodTracing("simple.trace");
|
在方法执行终止处添加:
1
| Debug.stopMethodTracing();
|
执行完毕会自动将方法执行信息写入外部存储Android/data/包名/file目录下。
启动速度分析工具 —— Systrace
生成Html分析文件