Java实现代码执行时间计算:从时间戳到运行时长详解

在Java中,你可以使用System.currentTimeMillis()System.nanoTime()来获取时间戳,然后计算代码的运行时长。以下是几种实现方式:

图片[1]_Java实现代码执行时间计算:从时间戳到运行时长详解_知途无界

1. 使用 System.currentTimeMillis()(毫秒级精度)

public class ExecutionTimeExample {
    public static void main(String[] args) {
        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 模拟耗时操作
        try {
            Thread.sleep(1000); // 休眠1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 记录结束时间
        long endTime = System.currentTimeMillis();

        // 计算运行时长(毫秒)
        long duration = endTime - startTime;

        System.out.println("代码运行时长: " + duration + " 毫秒");
    }
}

输出示例:

代码运行时长: 1001 毫秒

2. 使用 System.nanoTime()(纳秒级精度,适合高精度测量)

public class NanoTimeExample {
    public static void main(String[] args) {
        // 记录开始时间(纳秒)
        long startTime = System.nanoTime();

        // 模拟耗时操作
        for (int i = 0; i < 1000000; i++) {
            // 空循环模拟计算
        }

        // 记录结束时间
        long endTime = System.nanoTime();

        // 计算运行时长(纳秒)
        long durationNano = endTime - startTime;

        // 转换为毫秒(可选)
        double durationMillis = durationNano / 1_000_000.0;

        System.out.println("代码运行时长: " + durationNano + " 纳秒");
        System.out.println("代码运行时长: " + durationMillis + " 毫秒");
    }
}

输出示例:

代码运行时长: 456789 纳秒
代码运行时长: 0.456789 毫秒

3. 封装成工具类(推荐)

public class TimeUtils {
    /**
     * 计算代码执行时间(毫秒)
     */
    public static void measureExecutionTime(Runnable codeBlock) {
        long startTime = System.currentTimeMillis();
        codeBlock.run();
        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时: " + (endTime - startTime) + "ms");
    }

    /**
     * 计算代码执行时间(纳秒)
     */
    public static void measureExecutionTimeNano(Runnable codeBlock) {
        long startTime = System.nanoTime();
        codeBlock.run();
        long endTime = System.nanoTime();
        System.out.println("执行耗时: " + (endTime - startTime) + "ns");
    }

    public static void main(String[] args) {
        // 测试工具类
        TimeUtils.measureExecutionTime(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        TimeUtils.measureExecutionTimeNano(() -> {
            int sum = 0;
            for (int i = 0; i < 1000000; i++) {
                sum += i;
            }
        });
    }
}

输出示例:

执行耗时: 501ms
执行耗时: 1234567ns

4. 使用 Java 8 的 Instant(更现代的API)

import java.time.Duration;
import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant start = Instant.now();

        // 模拟耗时操作
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Instant end = Instant.now();

        // 计算时间差
        Duration duration = Duration.between(start, end);

        System.out.println("代码运行时长: " + duration.toMillis() + " 毫秒");
        System.out.println("代码运行时长: " + duration.toNanos() + " 纳秒");
    }
}

输出示例:

代码运行时长: 1501 毫秒
代码运行时长: 1501000000 纳秒

总结

方法精度适用场景特点
System.currentTimeMillis()毫秒通用计时简单易用,受系统时间影响
System.nanoTime()纳秒高精度测量适合短时间测量,不受系统时间影响
Instant + Duration纳秒Java 8+更现代,支持时间运算
工具类封装自定义复用代码推荐用于项目中的性能测试

选择方法时:

  • 需要高精度(如算法性能测试) → 用 nanoTime()
  • 普通场景(如接口耗时统计) → 用 currentTimeMillis()Instant
  • 需要复用 → 封装成工具类
© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞66 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容