闲着没事就想测试下程序运行代码的时间,搜了两个测试代码的方法,和大家一起分享:
1.以毫秒为单位(ms)
public static void main(String[] args) {
//get start time
long startTime = System.currentTimeMillis();
//test the code
test code
//get the end time
long endTime = System.currentTimeMillis();
System.out.println("take the time is: " + (endTime - startTime) + " ns")
}
2.以纳秒为单位
public static void main(String[] args) {
//get start time
long startTime = System.nanoTime();
//test the code
test code
//get the end time
long endTime = System.nanoTime();
System.out.println("take the time is: " + (endTime - startTime) + " ms")
}
END......
本文介绍两种测试Java代码执行时间的方法,一种是以毫秒为单位,使用`System.currentTimeMillis()`;另一种是以纳秒为单位,使用`System.nanoTime()`。通过对比开始时间和结束时间来计算代码执行所需时间。

被折叠的 条评论
为什么被折叠?



