1、一般我们检测某段代码执行的时间,都是以如下方式来进行的:
public static void main(String[] args) {
long startTime=System.currentTimeMillis(); //获取开始时间
//函数主体代码
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
}
2、Guava中com.google.common.base.Stopwatch使用:
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.base.Stopwatch;
public class GuavaTest {
@Test
public void testStopwatch() throws InterruptedException {
// 创建自动start的计时器
Stopwatch watch = Stopwatch.createStarted();
Thread.sleep(1000L);
long time = watch.elapsed(TimeUnit.MILLISECONDS);
// 结果1003
System.out.println("代码执行时长:" + time);
// 创建非自动start的计时器
// 累计了start到stop的时间
Stopwatch watch1 = Stopwatch.createUnstarted();
watch1.start();
Thread.sleep(1000L);
watch1.stop();
watch1.start();
Thread.sleep(500L);
time = watch1.elapsed(TimeUnit.MILLISECONDS);
// 结果1500
System.out.println("代码执行时长:" + time);
Stopwatch watch2 = Stopwatch.createUnstarted();
watch2.start();
Thread.sleep(1000L);
time = watch2.elapsed(TimeUnit.MILLISECONDS);
// 结果1000
System.out.println("代码执行时长:" + time);
}
}
3、Apache中org.apache.commons.commons-lang3.Stopwatch使用:
3.1、引入依赖jar包:
3.2、方法:
start();//开始计时
split();// 设置 split 点
getSplitTime();// 获取从 start 到最后一次 split 的时间
reset();//重置计时
suspend();//暂停计时
resume();// 恢复计时
stop();// 停止计时
getTime();// 统计从 start 到现在的计时
3.3、上代码:
3.3.1、public static void main(String[] args) {
//创建并启动StopWatch
StopWatch stopwatch = StopWatch.createStarted();
//业务逻辑......
stopwatch.stop();
System.out.println(stopwatch.getTime(TimeUnit.MINUTES));
}
3.3.2、public static void main(String[] args) {
StopWatch stopWatch = new StopWatch();
// 计时开始点
stopWatch.start();
// do something ...
Thread.sleep(1000);
// 断点1
stopWatch.split();
Thread.sleep(1000);
System.out.println(stopWatch.getSplitTime());
// 断点2
stopWatch.split();
// 暂停计时
stopWatch.suspend();
Thread.sleep(1000);
System.out.println(stopWatch.getSplitTime());
// 恢复计时
stopWatch.resume();
Thread.sleep(500);
// 获取从 start 到 现在的计时
System.out.println(stopWatch.getTime());
}
3.3.3、public static void main(String[] args) {
StopWatch sw = new StopWatch();
sw.start();
Thread.sleep(1000L);
System.out.println(sw.getTime());
sw.reset();
sw.start();
Thread.sleep(1000L);
System.out.println(sw.getTime());
}