【Java】一个小程序,计算它包含的代码所需的耗时

时间:2022-02-14 09:34:01

写一个小程序,用来计算它包含的代码所需的耗时。虽然简单,测试代码是否耗时还是有点用的,不用重新写嘛~

import java.util.Date;
import java.util.concurrent.TimeUnit; public class TimeLag { private Date start;
private Date end; public TimeLag() {
start = new Date();
} public String cost() {
end = new Date();
long c = end.getTime() - start.getTime(); String s = new StringBuffer().append("cost ").append(c).append(" milliseconds (").append(c / 1000).append(" seconds).").toString();
return s;
} public static void main(String[] args) throws InterruptedException {
TimeLag t = new TimeLag();
TimeUnit.SECONDS.sleep(2);
System.out.println(t.cost());
} }