Java-统计程序运行的时长(计算两个时间相差的毫秒数、秒数)

最近在做Hbase的查询性能验证,需要统计查询的执行时长,所以需要统计开始时间和结束时间的时间差。

下面是使用SimpleDateFormat和Date计算时间差(相差毫秒数)的程序示例,仅供参考。

package com.sgcc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

    public static long timeDiff(String startTime, String endTime) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long diff;
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return diff;
    }

    public static void main(String[] args) {

        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String startTime = sdf.format(new Date());
        try {
            Thread.sleep(1200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String endTime = sdf.format(new Date());
        System.out.println(timeDiff(startTime,endTime)+"ms");

    }
}

 【改进版本】时间差可以自动按照时间单位(小时、分钟、秒、毫秒)显示,四舍五入保留2位小数。

package com.sgcc;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

    public static String timeDiff(String startTime, String endTime,String timeUnit) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        DecimalFormat df = new DecimalFormat("#.00");
        long diff;
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if (timeUnit.equals("h")){
            double diffHour = Double.parseDouble(df.format(diff / (1000.0*3600)));
            return diffHour + "h";
        }
        else if (timeUnit.equals("min")){
            double diffMin = Double.parseDouble(df.format(diff / (1000.0*60)));
            return diffMin + "min";
        } else if(timeUnit.equals("s")){
            double diffSeconds = Double.parseDouble(df.format(diff / 1000.0));
            return diffSeconds + "s";
        }else if(timeUnit.equals("ms")){
            return diff + "ms";
        }else{
            System.out.println("time unit is wrong! The default result returns millisecond.");
            return diff + "ms";
        }
    }

    public static void main(String[] args) {

        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String startTime = sdf.format(new Date());
        try {
            Thread.sleep(1599);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String endTime = sdf.format(new Date());

        System.out.println(timeDiff(startTime,endTime,"s"));

    }
}

 

posted @ 2023-09-27 16:22  业余砖家  阅读(412)  评论(0编辑  收藏  举报