java分析测试代码程序执行时间与消耗内存

本文介绍了一种在IDEA中自定义实现的性能测试工具,该工具能够测量Java程序的执行时间和内存消耗,并提供了一段示例代码及使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 最近刷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方法中只执行这两个方法,来查看误差时间值。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

请保持优秀。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值