您可以使用 Date 类以毫秒为单位获取之前和之后的时间。我确信有一个更优雅的解决方案,不要投票太多)
public static void main(String[] args) {
long d = new Date().getTime();
//Ваш код
doSomething();
//конец вашего кода
long e = new Date().getTime();
System.out.println(e-d);
}
public static void doSomething(){
int count=0;
while (count<200){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
LocalDateTime from = LocalDateTime.now();
for (int i = 0; i < 1_000_000; i++) {
integers.add(i);
}
LocalDateTime to = LocalDateTime.now();
System.out.println(Duration.between(from, to).toMillis());
}
您可以使用 Date 类以毫秒为单位获取之前和之后的时间。我确信有一个更优雅的解决方案,不要投票太多)
使用测量代码执行时间
如果代码在几秒钟内没有执行,这是一个坏主意,即使结果将取决于测量时 jvm 的状态和其他因素。我建议您阅读 Alexey Shipelev 关于 Java 性能的报告。youtube上有很多。要测量代码执行时间,您应该使用特殊的框架,例如 JMH https://github.com/openjdk/jmh
代码将循环将 1,000,000 个项目添加到列表所需的时间(以毫秒为单位)打印到控制台。