Android修炼之道—时间测量
16lz
2021-12-04
Java 和 Android提供了一下API, 可以测量时间及性能:
System.currentTimeMillis
System.nanoTime
//下面是Android独有的
Debug.threadCpuTimeNanos
SystemClock.currentThreadTimeMillis
SystemClock.elapsedRealtime
SystemClock.uptimeMillis
尽管System.currentTimeMillis()可以作为测量时间的手段,但不建议使用这种方法来评测性能,原因如下:
其精度和准确度可能不够;
更改系统时间会影响结果。
最好使用System.nanoTime(),因为它提供了更好的精度和准确度。
System.nanoTime()
System.nanoTime()没有定义参考时间,它只能用来测量时间间隔,而用System.currentTimeMillis(),它返回的是UTC
时间1970年1月1日00:00:00到现在的毫秒数。
Debug.threadCpuTimeNanos()
应为Debug.threadCpuTimeNanos()只测量在当前线程所花费的时间,所以它的结果更准确。用法和System.nanoTime()一样,
只用于测量时间间隔。
Debug.startMethodTracing()
Android提供了Debug.startMethodTracing()方法来创建跟踪文件,然后用Traceview工具调试和分析应用。
Debug.startMethodTracing()方法有4个变种:
startMethodTracing()
startMethodTracing(String traceName)
startMethodTracing(String traceName, int bufferSize)
startMethodTracing(String traceName, int bufferSize, int flags)
traceName参数指定写入跟踪信息的文件名。
Debug.startMethodTracing("/sdcard/awesometrace.trace");
//需要跟踪的操作
BigInteger fN = Fibonacci.computeRecursivelyWithCache(100000);
Debug.stopMethodTracing();
//现在在/mnt/sdcard/目录下会有awesometrace.trace文件,在Eclipse DDMS中可以取到
System.currentTimeMillis
System.nanoTime
//下面是Android独有的
Debug.threadCpuTimeNanos
SystemClock.currentThreadTimeMillis
SystemClock.elapsedRealtime
SystemClock.uptimeMillis
尽管System.currentTimeMillis()可以作为测量时间的手段,但不建议使用这种方法来评测性能,原因如下:
其精度和准确度可能不够;
更改系统时间会影响结果。
最好使用System.nanoTime(),因为它提供了更好的精度和准确度。
System.nanoTime()
System.nanoTime()没有定义参考时间,它只能用来测量时间间隔,而用System.currentTimeMillis(),它返回的是UTC
时间1970年1月1日00:00:00到现在的毫秒数。
Debug.threadCpuTimeNanos()
应为Debug.threadCpuTimeNanos()只测量在当前线程所花费的时间,所以它的结果更准确。用法和System.nanoTime()一样,
只用于测量时间间隔。
Debug.startMethodTracing()
Android提供了Debug.startMethodTracing()方法来创建跟踪文件,然后用Traceview工具调试和分析应用。
Debug.startMethodTracing()方法有4个变种:
startMethodTracing()
startMethodTracing(String traceName)
startMethodTracing(String traceName, int bufferSize)
startMethodTracing(String traceName, int bufferSize, int flags)
traceName参数指定写入跟踪信息的文件名。
Debug.startMethodTracing("/sdcard/awesometrace.trace");
//需要跟踪的操作
BigInteger fN = Fibonacci.computeRecursivelyWithCache(100000);
Debug.stopMethodTracing();
//现在在/mnt/sdcard/目录下会有awesometrace.trace文件,在Eclipse DDMS中可以取到
更多相关文章
- Android获取当前时间
- 日期和时间(DatePicker、TimePicker)
- android:获取网络时间、文件路径,修改包名,发布release版本
- Android性能测试
- Android时区问题
- android默认系统日期、时间、时区更改
- Android--MediaPlayer音乐播放器歌词随时间高亮显示
- Android:CountDownTimer 实现倒计时功能
- Android(安卓)控件之DatePicker,TimePicker,Calender