计算程序耗时工具
计算程序耗时工具
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
	}
split分段:与上面的方式并无差别
    @Test
	public void test() throws InterruptedException {
		StopWatch stopWatch = StopWatch.createStarted();
		Thread.sleep(1000);
		stopWatch.split();
		System.out.println(stopWatch.formatSplitTime()); // 00:00:01.004
		Thread.sleep(2000);
		stopWatch.split();
		System.out.println(stopWatch.formatSplitTime()); // 00:00:03.016
		System.out.println(stopWatch.toString()); // 00:00:03.016
	}
    
以上每个分段计时都是累计耗时,如果想要每段独立的耗时,需要自行处理下
	@Test
	public void test() throws InterruptedException {
		StopWatch stopWatch = StopWatch.createStarted();
		Thread.sleep(1000);
		stopWatch.split();
		long sp1 = stopWatch.getSplitTime();
		System.out.println(DurationFormatUtils.formatDurationHMS(sp1)); // 00:00:01.003
		Thread.sleep(2000);
		stopWatch.split();
		long sp2 = stopWatch.getSplitTime();
		System.out.println(DurationFormatUtils.formatDurationHMS(sp2 - sp1)); // 00:00:02.012
		System.out.println(stopWatch.toString()); // 00:00:03.016
	}
    边系鞋带边思考人生.
                    
                
                
            
        
浙公网安备 33010602011771号