1 import com.google.common.base.Stopwatch;
2 import lombok.extern.slf4j.Slf4j;
3
4 import java.util.concurrent.TimeUnit;
5
6 @Slf4j
7 public class StopwatchUtils {
8 private static ThreadLocal<Stopwatch> stopwatchThreadLocal = new ThreadLocal<>();
9
10
11 public static void start() {
12 //本线程计时器
13 if (stopwatchThreadLocal == null || stopwatchThreadLocal.get() == null) {
14 stopwatchThreadLocal.set(Stopwatch.createStarted());
15 }
16 stopwatchThreadLocal.get().start();
17 }
18
19
20 /**
21 * 统计代码执行时间
22 *
23 * @param title
24 */
25 public static void printCodeExecTime(String title) {
26 //本线程计时器
27 if (stopwatchThreadLocal == null || stopwatchThreadLocal.get() == null) {
28 stopwatchThreadLocal.set(Stopwatch.createStarted());
29 }
30 /* ============================================统计耗时===================================================================== */
31 // 停止计时器 // 执行统计// 清空计时器// 再次启动统计
32 stopwatchThreadLocal.get().stop();
33 log.info("==========耗时统计"
34 + "==========" + title
35 + "==========线程名字:" + Thread.currentThread().getName()
36 + "==========线程id:" + Thread.currentThread().getId()
37 + "==========执行时长(毫秒) : "
38 + stopwatchThreadLocal.get().elapsed(TimeUnit.MILLISECONDS));
39 stopwatchThreadLocal.get().reset();
40 stopwatchThreadLocal.get().start();
41 /* ============================================统计耗时===================================================================== */
42 }
43
44
45 public static void end() {
46 stopwatchThreadLocal.get().stop();
47 stopwatchThreadLocal.remove();
48 }
49 }