Java program performance test

xiaoxiao2021-03-06  72

Java program performance test

1 Overview

In development, performance testing is an early date of design, and the developer will "unscrupulously" in order to solve a problem. The author participated in the project has encountered similar problems, string stitching, a large number of network calls and database access, etc. All have an impact on the performance of the system, but everyone will not care about these problems, "CPU speed is changing", "there is a big", "it seems to be so slow".

There are many commercial performance test software available, such as JProfiler, Jprobe Profiler, etc., but it seems distant and expensive in development.

2 goal

This article will tell how to use the method provided by Java language itself to perform performance testing in development, find system bottlenecks, and improve design; and test it without modifying test objects.

3 preparatory knowledge

Object-oriented programming by abstract inheritance adopts modular ideas to solve the problem domain, but modularity can't solve all problems well. Sometimes these problems may appear in multiple modules, like logging, in order to record each method to enter and leave information, you have to add log ("in some method") and other information in each method. How to solve this type of problem? Practice these functional points of these solutions will increase the redundancy in multiple modules, and when many function points appear in one module, the code changes difficult to maintain. Therefore, AOP (Aspect Oriented Programming) came into being. If OOP (AObject Oriented Programming is concerned about a vertical structure of a class, AOP is a problem from a horizontal perspective.

Dynamic proxy classes can implement several interfaces at runtime, each dynamic proxy class has an Invocation Handler object, and this object implements the InvocationHandler interface. The method of calling the dynamic agent object will be called through the interface of the dynamic agent. Invoke method of the Invocation Handler object, by dynamic proxy instance, method object, and parameter objects can perform calls and return results.

Speaking of AOP, everyone will first think about logging, permission checks, and transaction management, yes, AOP is a good way to solve these problems. This article solves a new type of problem-performance test by dynamic agents according to the idea of ​​AOP, and Performance Testing.

Performance test mainly includes the following aspects:

l Computation performance: Maybe people first care, simple saying is the time used to perform a code.

l Memory consumption: The memory size occupied by the program run

l Start time: time from your launch procedure to the normal operation

l Scalability (SCALABILITY)

l Users perceived Performance: Not how fast the program actually runs, but how fast the user feels running.

This paper mainly gives a feasibility of calculating performance testing and memory consumption testing.

4 calculate performance test

4.1 Target:

You can get a method for performing a time to do

4.2 Implementation:

Java provides us with the system. Currenttimemillis () method, you can get the current time of milliseconds, and we have written similar code in the previous program to calculate the time consumed by the execution of a piece of code.

Long Start = system.currenttimemillis (); dost (); long end = system.currenttimemillis (); system.out.println ("time lasts" (end-start) "MS"); however, in each method It is a very boring thing to write such a code, we use the dynamic agent to solve the above problems through Java.lang.Reflect.Proxy and Java.lang.Reflect.invocationHandler use dynamic agents.

The example we want to test is the Get (int index) method of java.util.linkedList and Java.util.ArrayList, apparently arraylist is efficient than LinkedList because the former is random access, while the latter needs sequential access.

First we create an interface

Public interface foo {public void testArrayList (); public void testlinkedList ();

Then we create test objects to implement this interface

Public class fooImpl imports foo {

Private list link = new linkedList (); private list array = new arraylist ();

Public fooImpl () {for (int i = 0; i <10000; i ) {Array.Add (New Integer (i)); link.add (new integer (i));}}}} public void testArrayList () {for (INT i = 0; i <10000; i ) array.get (i);} public void testlinkedList () {for (int i = 0; i <1000; i ) link.get (i);}}

Next, we must do a key step to implement the InvocationHandler interface.

Import java.lang.reflect.invocationhandler; import java.lang.reflect.method; import java.lang.reflect. *;

Public Class Handler IMPLEments InvocationHandler {

Private Object Obj;

Public Handler (Object Obj) {this.obj = Obj;}

Public static object newinstance (object obj) {Object results = proxy.newproxyinstance (Obj.getClass (). getClassLoader (), obj.getClass (). getInterface (), new handler ());

Return (Result);

Public Object Invoke (Object Proxy, Method Method, Object [] args) throws throwable {Object Result; Try {system.out.print ("Begin Method" Method.GetName () "("); for (int i = 0; args! = Null && i 0) System.out.Print (","); system.out.print (" args [i] .tostring () } System.out.println (")"); long start = system.currenttimemillis (); result = method.invoke (Obj, args); long end = system.currenttimemillis (); system.out.println (" 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 {system.out.println ("end me Thod " method.getname ());} Return Result;}}

Finally, we create test clients,

Public class testproxy {public static void main (string [] args) {try {foo foo = (foo) handler.newinstance (new fooImpl ()); foo.testarrayList (); foo.testlinkedList ();} catch (Exception E ) {E.PrintStackTrace ();}}}

The results of operation are as follows:

Begin Method TestarrayList ()

The Method TestarrayList Lasts 0ms

End Method TestarrayList

Begin method TestlinkedList ()

The Method TestlinkedList Lasts 219ms

End method testlinkedList uses the advantages of dynamic agents to use the original code fooImpl, but a disadvantage is that you have to write an interface, if your class does not implement the interface.

4.3 expansion

In the above example demonstrates the execution time of the two methods of comparing the dynamic proxy, sometimes the comparison is a one-way test, so that the test object can be performed multiple times, thereby calculating the worst, preferably peace average performance. In this way, we can "accelerate the speed of the procedure that is often performed, try to use less speeds". "

5 memory consumption test

5.1 Goal

When a Java application is running, there are many factors that need to consume memory, like objects, load classes, threads, etc. Only the virtual machine stack space consumed by the object in the program, so we can use the runtime class's FreeMemory () and TotalMemory () methods.

5.2 implementation

For convenience, we first add a class to calculate the current memory consumption.

Class memory {public static long = runtime.getRuntime (). TotalMemory (); long free = runtime.getime (). freeMemory (); return (Total-free);}

Then modify the INVOKE () method of the Handler class.

Public Object Invoke (Object Proxy, Method Method, Object [] args) throws throwable {Object Result; Try {system.out.print ("Begin Method" Method.GetName () "("); for (int i = 0; Args! = NULL && I

IF (i> 0) system.out.print (","); system.out.print (" args [i] .tostring ());} system.out.println (") "); long start = Memory.Used (); result = method.invoke (obj, args); long end = memory.used (); system.out.println ("Memory Increaged By" "BYTES"); } catch (InvocationTargetException e) {throw e.getTargetException ();} catch (Exception e) {throw new RuntimeException ( "unexpected invocation exception:" e.getMessage ());} finally {System.out.println ( "end Method " Method.getName ());} Return Result;} At the same time, our test case also made changes, test the same obnegant problem, compares the size, interface, interface, The implementation is as follows:

Public interface memoconsumer {public void create (); public void creathashmap ();} public class memoconsumerimpl imports memoconsumer {

ArrayList Arr = NULL; Hashmap Hash = NULL;

Public void create marray () {

Arr = new arraylist (1000); public void creathashmap () {hash = new hashmap (1000);}}

The test client code is as follows:

Memoconsumer arraymemo = (memoconsumer) Handler.newinstance (New memoConSuMPL ()); arrayMemo.creatarray (); ArrayMemo.creathashMap ();

The test results are as follows:

Begin method CreatArray ()

Memory increased by 4400bytes

End Method CreatArray

Begin Method CreathashMap ()

Memory increased by 4480bytes

End Method CreathashMap

As a result, you can see that we only need to modify the invoke () method, and then the client calls can be called. 6 Conclusion

AOP has completed the decomposition points and OOP, making the program more simple and easy, and the dynamic agent provided by Java language itself helps us easily break down concerns, and achieve better results. However, the test object must implement the interface to a certain extent, which can use the CGLIB used in Spring to create a dynamic agent for classes that do not implement any interfaces.

7 References

Some of the performance test concepts mentioned herein are mainly from http://java.sun.com/docs/books/performance/

Some concepts of AOP http://www.jboss.org/index.html?module =html&op=userdisplay&id=develop/projects/jboss/AOP

Some knowledge of dynamic proxy and AOP comes from http://www.springframework.org/docs/reference/aop.html

8 author declaration

Writing is generally written, but my hard work is, please indicate the source, you can contact me through whq3721@163.com, http://freshman.52blog.net

转载请注明原文地址:https://www.9cbs.com/read-86988.html

New Post(0)