Android修炼之道—时间测量

本文探讨了在Android中测量时间和性能的方法,包括System.currentTimeMillis(), System.nanoTime(), Debug.threadCpuTimeNanos()以及Debug.startMethodTracing()。强调了System.nanoTime()的高精度和Debug.threadCpuTimeNanos()对于线程特定时间测量的准确性,并介绍了Debug.startMethodTracing()用于生成跟踪文件以进行应用调试和分析。" 112126665,10548258,隐私保护与广告效果追踪:bcrypt与集合交集加密算法,"['数据安全', '隐私保护', '广告技术', '加密算法', '集合交集']

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

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中可以取到
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值