计算程序耗时工具

计算程序耗时工具

public class TimeConsumptionDemo {

	public static void main(String[] args) throws InterruptedException {
		long begin = System.currentTimeMillis(); 
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println(String.format("程序执行耗时:%s", diffTime(begin,end)));
	}
	
	
	/**
	 * Desc: 计算时间差  方式一
	 * long begin = System.currentTimeMillis(); 
	 * long end = System.currentTimeMillis();
	 * @param begin
	 * @param end
	 * @return
	 */
	public static String diffTime(long begin, long end) {
		long diff = Math.abs(end - begin);
		long days = diff / (1000 * 60 * 60 * 24);   
		long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60); //获取时 
        long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  //获取分钟
        long s=(diff/1000-days*24*60*60-hours*60*60-minutes*60);//获取秒
        return hours+"时"+minutes+"分"+s+"秒";
	}
	
	

}

方式2:使用org.apache.commons.lang3.time.StopWatch 计时

import org.apache.commons.lang3.time.StopWatch;
StopWatch sw = StopWatch.createStarted();
Thread.sleep(5000);
System.out.println(String.format("程序执行耗时:%s", sw));

// 测试分段计时
	@Test
	public void testConsumeTime() throws InterruptedException {
		StopWatch sw = StopWatch.createStarted();
		Thread.sleep(3 * 1000);
		System.out.println("consume: "+sw);  // 3
		Thread.sleep(2 * 1000);
		System.out.println("consume2: " + sw);  // 5
	}
posted @ 2021-08-23 16:21  穷苦书生  阅读(84)  评论(0编辑  收藏  举报