最近刷LeetCode题的时候,突然想用idea分析每个程序执行消耗的时间和内存,但是网上搜了一下好像也没明确说明要怎么办的,看了几篇类似的帖子,自己造了一个java单例类,定义了start和end方法来分析两个方法之间代码的执行。
代码如下:
package LeetCode.util;
/**
* @author 肖航
* @date 2019/7/18
* @description 测试代码使用的时间与内存。
*/
public class Examination {
public static long concurrentTime1, concurrentTime2, concurrentMemory1, concurrentMemory2;
public static void start() {
//得到程序开始时的系统时间(纳秒级,最终转化毫秒,保留小数点后两位)
concurrentTime1 = System.nanoTime();
//得到虚拟机运行、程序开始执行时jvm所占用的内存。
Runtime runtime = Runtime.getRuntime();
concurrentMemory1 = runtime.totalMemory()-runtime.freeMemory();
}
public static void end() {
//得到程序执行完毕时的系统时间(毫秒级)
concurrentTime2 = System.nanoTime();
//得到虚拟机运行、所要测试的执行代码执行完毕时jvm所占用的内存(byte)。
Runtime runtime = Runtime.getRuntime();
concurrentMemory2 = runtime.totalMemory()-runtime.freeMemory();
//计算start和end之间的代码执行期间所耗时间(ms)与内存(M)。
// 1毫秒(ms) = 1000微秒(us) = 1000 000纳秒(ns)
// 1M = 1*2^20 byte = 1024 * 1024 byte;
String time = String.valueOf((double)(concurrentTime2 - concurrentTime1)/1000000);
String memory = String.valueOf((double)(concurrentMemory2-concurrentMemory1)/1024/1024) ;
System.out.println("---------------您的代码执行时间为:" + time.substring(0,time.equals("0.0") ? 1 : (time.indexOf(".")+3)) + " ms, 消耗内存:" + memory.substring(0,memory.equals("0.0") ? 1 : (memory.indexOf(".")+3)) + " M + !---------------");
}
}
使用方法:
Examination.start();
//在此处输入测试代码段
Examination.end();
其中end方法会输出代码段的时间和内存。其中要注意的是以下几行代码的执行本身就要消耗一定的时间:
concurrentTime1 = System.nanoTime();
Runtime runtime = Runtime.getRuntime();
concurrentMemory1 = runtime.totalMemory()-runtime.freeMemory();
concurrentTime2 = System.nanoTime();
Runtime runtime = Runtime.getRuntime();
concurrentMemory2 = runtime.totalMemory()-runtime.freeMemory();
实测这几行代码的执行时间为0.06ms左右,也就是说结果会有0.06ms左右的误差,而内存则不存在这个问题。
您也可以在main方法中只执行这两个方法,来查看误差时间值。