计算代码执行时间的工具类方法1

2026年01月23日 07:47

描述

使用 ThreadLocal 为每个线程保存独立的开始时间

标签

Java
计算代码执行时间的工具类方法1.txt 1,891 字符 | 49 行
import java.util.Locale;

public class UseTime {
    // 使用 ThreadLocal 为每个线程保存独立的开始时间
    private static final ThreadLocal<Long> threadStartTime = new ThreadLocal<>();

    public static void startPrintTime() {
        long currentTime = System.currentTimeMillis();
        threadStartTime.set(currentTime); // 设置当前线程的开始时间
        System.out.println("[" + Thread.currentThread().getName() + "] 开始时间: " +
                KentDataTime.getYYMMDDHHMMSSSSSString());
    }

    public static void endPrintTime() {
        Long startTime = threadStartTime.get();
        if (startTime == null) {
            System.err.println("[" + Thread.currentThread().getName() + "] 警告: 请先调用 startPrintTime()");
            return;
        }

        System.out.println("[" + Thread.currentThread().getName() + "] 结束时间: " +
                KentDataTime.getYYMMDDHHMMSSSSSString());
        System.out.println("[" + Thread.currentThread().getName() + "] " +
                getFormattedDuration(startTime, System.currentTimeMillis()));

        // 可选:清理ThreadLocal,避免内存泄漏(特别是线程池场景)
        threadStartTime.remove();
    }

    private static String getFormattedDuration(long startTimeMillis, long endTimeMillis) {
        long durationMillis = endTimeMillis - startTimeMillis;
        if (durationMillis < 0) {
            throw new IllegalArgumentException("结束时间不能早于开始时间");
        }

        long totalSeconds = durationMillis / 1000;
        long minutes = totalSeconds / 60;
        long seconds = totalSeconds % 60;
        long millis = durationMillis % 1000;

        String formatString = "花费了 %02d 分钟 %02d 秒 %03d 毫秒 (总计: %d毫秒)";
        return String.format(Locale.CHINA, formatString, minutes, seconds, millis, durationMillis);
    }

    // 新增:手动清理方法(用于线程池环境)
    public static void clearCurrentThreadTime() {
        threadStartTime.remove();
    }
}

支持 Ctrl+A 全选,Ctrl+C 复制