性能测试之计算性能

计算性能,简单的说就是执行一段代码所用的时间。

我们在以前一定写过类似代码来计算执行某一段代码所消耗的时间:

long start = System.currentTimeMillis();

long end = System.currentTimeMillis();

System.out.println(“time lasts ” + (end – start) + “ms”);

在每个方法中都写上这么一段代码是一件很枯燥的事情,我们通过java.lang.reflect.Proxy和java.lang.reflect.InvocationHandler利用动态代理来很好地解决上面的问题。

++ 实现InvocationHandler接口 ++

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 = System.currentTimeMillis();

      result = method.invoke(obj, args);

      long end = System.currentTimeMillis();

      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());

    }

  }

}

++  应用Handler类测试计算性能  ++

public interface Testing {

  public void testArrayList();

  public void testLinkedList();

}

public class TestingImpl implements Testing {

  public void testArrayList(){…}

  public void testLinkedList(){…}

}

// 测试代码

Testing testing = (Testing) Handler.newInstance(new TestingImpl());

testing.testArrayList();

testing.testLinkedList();

使用动态代理的好处是你不必修改原有代码FootImpl ,但是有一个缺点--如果你的类原来没有实现接口,你不得不写一个接口。

上面的例子演示了利用动态代理比较两个方法的执行时间,有时候通过一次简单的测试进行比较是片面的,因此可以进行多次执行测试对象,从而计算出最差、最好和平均性能。

原文地址:https://www.cnblogs.com/fengzhblog/p/3161822.html