• 优化技术之内存消耗测试


    2013-06-29

    内存消耗测试

    当一个Java应用程序运行时,有很多需要消耗内存的因素存在,如对象、加载类、线程等。在这里只考虑程序中的对象所消耗的虚拟机堆空间,这样我们就可以利用Runtime类的freeMemory()和totalMomery()方法。

    public class Handler implements InvocationHandler {

      private Object obj;

      public Handler(Object obj) {

        this.obj = obj;

      }

      public static Object newInstance(Object obj) {

        Object result = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new Handler(obj));

        return result;

      }

      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object result;

        try {

          Log.i(“Handler”, "begin method " + method.getName());

          long start = Memory.used();

          result = method.invoke(obj, args);

          long end = Memory.used();

          Log.i(“Handler”, "the method " + method.getName() + “ lasts ” + (end – start) + “ms”);

        } catch (InvocationTargetException e) {

          throw e.getTargetException();

        } catch (Exception e) {

          throw new RuntimeException(“unexpected invocation exception: ” + e.getMessage());

        } finally {

          Log.i(“Handler”, "end method " + method.getName());

        }

      }

    }

    public class Memory {

      public static long used() {

        long total = Runtime.getRuntime().totalMemory();

        long free = Runtime.getRuntime().freeMemory();

        return (total - free);

      }

    }

  • 相关阅读:
    由ping百度引发的思考
    操作系统 | 概述
    操作系统导论第四章 | 抽象:进程
    汇编语言 | 定制键盘输入的处理过程
    细数 TS 中那些奇怪的符号
    vue 各种 import 引入
    display:table-cell实现水平垂直居中
    Jquery判断单选框是否选中和获取选中的值
    css整理 -- 右箭头,上下箭头,三角形、超出省略号代替
    JQuery操作select下拉框
  • 原文地址:https://www.cnblogs.com/fengzhblog/p/3162370.html
Copyright © 2020-2023  润新知