写了一个demo,用traceview对里边的print()方法进行测试,最后的时间显示只是180ms。在print()方法前后使用System.currentTimeMillis()方式,时间值相差太远,原因是traceview在stopMethodTracing结束时候需要占用时间将缓存中的信息输出到*.trace文件中。
android.os.Debug.startMethodTracing("MainActivity-print");
long start = System.currentTimeMillis();
print();
android.os.Debug.stopMethodTracing();
long end = System.currentTimeMillis();
Log.i(LOG_TAG, "execute long : " + (end - start));
使用traceview测试时间为180ms
使用System.currentTimeMillis()方式进行为1105ms.
原因就在于
android.os.Debug.stopMethodTracing();调用时,会消耗时间去将缓存中的内容输出到外部存储文件中。