nanoTime vs currentTimeMillis 比较
来源:互联网 发布:常用的mysql语句 编辑:程序博客网 时间:2024/06/14 12:40
System.nanoTime与System.currentTimeMillis比较
首先:
- currentTimeMillis返回的是系统当前时间和1970-01-01之前间隔时间的毫秒数,如果系统时间固定则方法返回值也是一定的(这么说是为了强调和nanoTime的区别),精确度是毫秒级别的
- nanoTime的返回值本身则没有什么意义,因为它基于的时间点是随机的,甚至可能是一个未来的时间,所以返回值可能为负数。但是其精确度为纳秒,相对高了不少。
- currentTimeMillis不仅可以用来计算代码执行消耗的时间 ,也可以和Date类方便的转换。而nanoTime则不行
- 可以这么说吧,currentTimeMillis是一个时钟,而nanoTime是一个计时器,你可以用时钟来计算时间差,也可以用来单纯的看时间,但是作为计时器的nanoTime则只能用来计算时间差,好在优点是精确度高
- currentTimeMillis是基于系统时间的,也就是说如果你再程序执行期间更改了系统时间则结果就会出错,而nanoTime是基于CPU的时间片来计算时间的,无法人为干扰
- 前面说了nanoTime基于的时间点是随机的,但是对于同一个JVM里,不同地方使用到的基点时间是一样的
下面是代码比较:
public class OptionTest { public static void main(String[] args) throws InterruptedException { for (int i = 1; i < 10; i++) { long start = System.nanoTime(); Thread.currentThread().sleep(1000); long end = System.nanoTime(); System.out.println(end-start); } }}//运行结果/*:100030814810004993581000593383100019476510003314561000969481100014775310002255811000201876*///(一毫米=1000000纳秒)//也就是说精确到毫秒级的话是无误差或是说误差很小
public class OptionTest { public static void main(String[] args) throws InterruptedException { for (int i = 1; i < 10; i++) { long start = System.currentTimeMillis(); Thread.currentThread().sleep(1000); long end = System.currentTimeMillis(); System.out.println(end-start); } }}/*:100110001001100010011001100010011001*///毫秒级并不准确
总结如下:
1.currentTimeMillis精度上相对于nanoTime要输很多
2.nanoTIme方法本身执行的时间相对于currentTimeMillis要多很多,所以应当只在精确度要求较高时使用nanoTime
3.currentTimeMillis是时钟,nanoTime是计时器
1 0
- nanoTime vs currentTimeMillis 比较
- System.nanoTime与System.currentTimeMillis比较
- java currentTimeMillis() nanoTime() 介绍
- nanoTime()与currentTimeMillis
- System.currentTimeMillis() 和 System.nanoTime();
- System.currentTimeMillis与System.nanoTime
- nanoTime()和currentTimeMillis()的区别
- system.nanoTime()和system.currentTimeMillis()
- System.nanoTime()和System.currentTimeMillis()区别 (还是直接看API比较清晰)
- System.nanoTime与System.currentTimeMillis的区别
- System.nanoTime与System.currentTimeMillis的区别
- System.nanoTime与System.currentTimeMillis的区别
- 关于System.currentTimeMillis()和System.nanoTime()
- System.nanoTime与System.currentTimeMillis的区别
- System.nanoTime与System.currentTimeMillis的区别
- System.nanoTime与System.currentTimeMillis的区别
- System.nanoTime与System.currentTimeMillis的区别
- System.nanoTime与System.currentTimeMillis的区别
- Oracle Dedicated server 和 Shared server(专用模式 和 共享模式) 说明
- XML
- 黑苹果显卡nVidia GTX 750 驱动 成功
- linux下安装mysql5.7
- 用数组实现队列--静态队列
- nanoTime vs currentTimeMillis 比较
- 《Nodejs开发加密货币》之十六:利益,魔鬼与天使的共同目标
- 字符串查找
- 线性表的链式存储结构
- Struts2-<s:doubleselect>标签 联动下拉框
- android View的scrollTo,scrollBy方法详解
- BZOJ3052 [wc2013]糖果公园
- leetcode 7. Reverse Integer
- ViewPager 结合Fragment实现一个Activity里包含多个可滑动的标签页