sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

java获取当前时间戳的三种方法比较效率(*)

获取当前时间戳

//方法 一
System.currentTimeMillis();
//方法 二
Calendar.getInstance().getTimeInMillis();
//方法 三
new Date().getTime();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

获取当前时间

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
  • 1
  • 2

获取时间戳三种方法执行效率比较:

import java.util.Calendar;
import java.util.Date;
public class TimeTest {
    private static long _TEN_THOUSAND=10000;
    public static void main(String[] args) {
        long times=1000*_TEN_THOUSAND;
        long t1=System.currentTimeMillis();
        testSystem(times);
        long t2=System.currentTimeMillis();
        System.out.println(t2-t1);
        testCalander(times);
        long t3=System.currentTimeMillis();
        System.out.println(t3-t2);
        testDate(times);
        long t4=System.currentTimeMillis();
        System.out.println(t4-t3);
    }
    public static void testSystem(long times){//use 188
        for(int i=0;i<times;i++){
            long currentTime=System.currentTimeMillis();
        }
    }
    public static void testCalander(long times){//use 6299
        for(int i=0;i<times;i++){
            long currentTime=Calendar.getInstance().getTimeInMillis();
        }
    }
    public static void testDate(long times){
        for(int i=0;i<times;i++){
            long currentTime=new Date().getTime();
        }
    }
}
  • 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
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

执行结果:
在这里插入图片描述
Calendar.getInstance().getTimeInMillis() 这种方式速度最慢,这是因为Canlendar要处理时区问题会耗费较多的时间。

时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。时间戳是一个加密文档,包含:文件的摘要、DTS收到文件的日期和时间以及DTS的数字签名三部分。它具有防篡改、防复用的优点。

https://blog.csdn.net/weixin_42408447/article/details/121799226
posted on 2022-10-09 13:04  sunny123456  阅读(1911)  评论(0编辑  收藏  举报