2022-12-29发表2022-12-29更新编程入门1 分钟读完 (大约186个字)测试程序运行时间程序本体123456789101112131415161718192021222324252627package com.example.util;import java.time.LocalDateTime;public class TimeUtil { public interface Task { void execute(); } public static void check(String title, Task task) { if (task == null) { return; } title = (title == null) ? "" : ("[" + title + "]"); System.out.println(title); System.out.println("开始:" + LocalDateTime.now()); long beginTime = System.currentTimeMillis(); task.execute(); long endTime = System.currentTimeMillis(); System.out.println("结束:" + LocalDateTime.now()); double delta = (endTime - beginTime) / 1000.0; System.out.println("耗时:" + delta + "秒"); System.out.println("========="); }} 调用12345678910111213141516171819package com.example;import com.example.util.TimeUtil;public class Main { public static void main(String[] args) { TimeUtil.check("testAdd", new TimeUtil.Task() { @Override public void execute() { long res = 0; for (long i = 0; i < 1000000000; i ++) { res += i; } System.out.println(res); } }); }} 运行结果 Python直接用time库就行12345678import time# 程序开始时的时间time_start = time.time()# 程序结束时系统时间time_end = time.time()# 两者相减print('totally cost', time_end - time_start)测试程序运行时间https://wyue1227.github.io/2022/12/29/编程入门/测试程序运行时间/作者Etsu发布于2022-12-29更新于2022-12-29许可协议#Java代码段Python