计算Java中任意一个方法的执行时间的工具类

如何获取一个方法的执行时间,不论是静态方法还是静态方法,不论是私有方法还是共有方法,如果该对象不能

被实例化,使用该对象的class对象也可以,例如Arrays.class也可以作为bean传入方法中

只有当方法是static,使用bean和bean.class都可以,但如果不是static,你使用bean.class 会报错

该方法主要用来计算一个方法的执行时间和是否打印方法的执行时间和输出结果,我制作这个方法主要用来比较排序算法的时间复杂度

下面是工具类的代码:

  1 package algorithm.study.utils;
  2 
  3 import java.lang.reflect.Method;
  4 
  5 /**
  6  * This class is getting a method execute time and provide some other functions.
  7  * 
  8  * @author ygh 2017年2月24日
  9  */
 10 public class MethodExecuteTimeUtils {
 11 
 12     /**
 13      * Get a method execute time using millisecond and cancel method's print return result and
 14      * execute time.
 15      * 
 16      * @param bean The method is in this bean
 17      * @param params The parameter the method execute need
 18      * @param methodName The name of the method
 19      * @param types The parameter type of the method
 20      * @return The execute time of this method
 21      * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail.
 22      */
 23     public static long getMethodExecuteTime(Object bean, Object[] params, String methodName, Class<?>[] types)
 24             throws Exception {
 25         return getMethodExecuteTime(bean, params, methodName, types, false, false);
 26     }
 27 
 28     /**
 29      * Get a method execute time using millisecond and cancel print method's return result.
 30      * 
 31      * @param bean The method is in this bean
 32      * @param params The parameter the method execute need
 33      * @param methodName The name of the method
 34      * @param types The parameter type of the method
 35      * @param isPrintExecutetime Whether print the execute time in console, true is print false not
 36      * @param isViewMehtodResult Whether print the return result in console, true is print false not
 37      * @return The execute time of this method
 38      * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail.
 39      */
 40     public static long getMethodExecuteTime(Object bean, Object[] params, String methodName,
 41             Class<?>[] types, boolean isPrintExecutetime) throws Exception {
 42         return getMethodExecuteTime(bean, params, methodName, types, isPrintExecutetime, false);
 43     }
 44 
 45     /**
 46      * Get a method execute time using millisecond and add some other service.
 47      * 
 48      * @param bean The method is in this bean
 49      * @param params The parameter the method execute need
 50      * @param methodName The name of the method
 51      * @param types The parameter type of the method
 52      * @param isPrintExecutetime Whether print the execute time in console, true is print false not
 53      * @param isViewMehtodResult Whether print the return result in console, true is print false not
 54      * @return The execute time of this method
 55      * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail.
 56      */
 57     public static long getMethodExecuteTime(Object bean, Object[] params, String methodName,
 58             Class<?>[] types, boolean isPrintExecutetime, boolean isViewMehtodResult) throws Exception {
 59         Class<?> clazz;
 60         long executeTime = -1L;
 61         boolean isAccessiable = false;
 62         Method method = null;
 63         if (bean instanceof Class<?>) {
 64             clazz = (Class<?>) bean;
 65         } else {
 66             clazz = bean.getClass();
 67         }
 68         try {
 69             if (types == null) {
 70                 method = clazz.getDeclaredMethod(methodName);
 71             } else {
 72                 method = clazz.getDeclaredMethod(methodName, types);
 73             }
 74             isAccessiable = method.isAccessible();
 75             if (!isAccessiable) {
 76                 method.setAccessible(true);
 77             }
 78 
 79             if (isViewMehtodResult) {
 80                 executeTime = getReturnMethodExecuteTime(bean, params, method);
 81             } else {
 82                 executeTime = getMethodExecuteTime(bean, params, method);
 83             }
 84             method.setAccessible(isAccessiable);
 85             if (isPrintExecutetime) {
 86                 printExecute(clazz, methodName, executeTime);
 87             }
 88         } catch (Exception e) {
 89             throw new Exception("excute method fail");
 90         }
 91         return executeTime;
 92     }
 93 
 94     /**
 95      * Get a method execute time, use millisecond. We don't think the method whether has a return
 96      * result
 97      * 
 98      * @param bean The method is in this bean
 99      * @param params The parameters the method execute need
100      * @param method The Method entity
101      * @return The millisecond the method execute spend
102      * @throws Exception If the method invoke fail
103      */
104     private static long getMethodExecuteTime(Object bean, Object[] params, Method method) throws Exception {
105         long startTime = System.currentTimeMillis();
106         method.invoke(bean, params);
107         long endTime = System.currentTimeMillis();
108         return endTime - startTime;
109     }
110 
111     /**
112      * Get a method execute time, use millisecond. The method must has a return result will input
113      * the return result in console ,If the method has not return result, please call
114      * <code>getMethodExecuteTime</code> method.
115      * 
116      * @param bean The method is in this bean
117      * @param params The parameters the method execute need
118      * @param method The Method entity
119      * @return The millisecond the method execute spend
120      * @throws Exception If the method invoke fail
121      */
122     private static long getReturnMethodExecuteTime(Object bean, Object[] params, Method method)
123             throws Exception {
124         long startTime = System.currentTimeMillis();
125         Object result = (Object) method.invoke(bean, params);
126         long endTime = System.currentTimeMillis();
127         if (result != null) {
128             System.out.println("result input:" + result.toString());
129         } else {
130             System.out.println("Warning:" + bean.getClass().getName() + "." + method.getName()
131                     + "has not return " + "result,please setting the isViewMehtodResult as false");
132         }
133         return endTime - startTime;
134     }
135 
136     /**
137      * Print the execute time of method
138      * 
139      * @param methodName The name of the method
140      * @param time The execute of the method
141      */
142     public static void printExecute(Class<?> clazz, String methodName, long time) {
143         System.out.println(clazz.getName() + "." + methodName + " execute time: " + time);
144     }
145 }

Person类,用于测试:

 1 package javareflect.demo;
 2 /**
 3  * This a person domain used test java.reflect
 4  * @author ygh 
 5  * 2017年2月26日
 6  */
 7 public class Person {
 8 
 9     private String name;
10     
11     private Integer age;
12     
13     private static String gender;
14     
15     public static String getGender(){
16         return gender;
17     } 
18     
19     public static void setGender(String gender){
20         System.out.println("性别:"+gender);
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     public Integer getAge() {
32         return age;
33     }
34 
35     public void setAge(Integer age) {
36         this.age = age;
37     }
38     
39     public static void fun1(){
40         System.out.println("this is fun1");
41     }
42     
43     private void fun2(){
44         System.out.println("this is private method");
45     }
46     
47     
48 }

下面是测试代码:测试执行Person类里面的各种Method,静态的,私有的,共有的

 1 public class ReflectTest {
 2     @Test
 3     public void fun1() throws Exception {
 4         Person person = new Person();
 5         Object[] params = null;
 6         Class<?>[] types = null;
 7         MethodExecuteTimeUtils.getMethodExecuteTime(person, params, "fun2", types, true, true);
 8     }
 9     @Test
10     public void fun2() throws Exception {
11         Person person = new Person();
12         Object[] params = null;
13         Class<?>[] types = null;
14         MethodExecuteTimeUtils.getMethodExecuteTime(person, params, "fun1", types, true, true);
15     }
16     @Test
17     public void fun3() throws Exception {
18         Person person = new Person();
19         Object[] params = {12};
20         Class<?>[] types = {Integer.class};
21         MethodExecuteTimeUtils.getMethodExecuteTime(person, params, "setAge", types, true, true);
22         System.out.println(person.getAge());
23     }
24 }

下面是测试代码,比较Java自带的排序方法和归并排序哪个时间复杂度更高。

  1 package algorithm.study.demo2;
  2 
  3 
  4 import java.util.Arrays;
  5 
  6 import org.junit.Test;
  7 
  8 import algorithm.study.utils.MethodExecuteTimeUtils;
  9 
 10 /**
 11  * This class implement MergeSort
 12  * @author ygh
 13  * 2017年2月23日
 14  */
 15 public class MergeSort {
 16 
 17     /**
 18      * Arithmetic thoughts:
 19      * If we want to sort a array elements,we can sort their left,then
 20      * sort their right. In the left array, we can use same thought
 21      * separate the left array to halt then sort them.....
 22      * At last,it will change into tow number compare,then merge
 23      * 
 24      * @param arr The array need to sort
 25      * @param A temporary array to store elements that have sorted,its length is right-left
 26      * 
 27      * @param left The left index of elements you want to sort in this array
 28      * @param right The right index of elements you want to sort in this array
 29      */
 30     public void mergeSort(int[] sortedArr,int[] tmpArr,int left,int right){
 31         if(left<right){
 32             int mid = (left+right) / 2;
 33             mergeSort(sortedArr,tmpArr, left, mid);
 34             mergeSort(sortedArr,tmpArr, mid+1, right);
 35             merge(sortedArr, tmpArr,left,mid,right);
 36             copy(sortedArr, tmpArr,left,right);
 37         }
 38     }
 39 
 40     /**
 41      * Copy elements from temporary array to sorted array. The index range is from left to rigth
 42      * @param haltSortedArr The array need to sort
 43      * @param tmpArr The temporary array
 44      * @param left The left index
 45      * @param right The right index
 46      */
 47     private void copy(int[] haltSortedArr, int[] tmpArr, int left, int right) {
 48         for(int i=left;i<=right;i++){
 49             haltSortedArr[i]=tmpArr[i];
 50         }
 51     }
 52 
 53     /**
 54      * This method is to merge elements from haltSortedArr.now the haltSortedArr 
 55      * has became sorted half by half.The elements' index from left to mid is sorted,and the
 56      * elements' index from mid to right is sorted.So we just need to merge it to get all order
 57      * array
 58      * @param haltSortedArr The array has became sorted half by half
 59      * @param tmpArr A temporary array to store elements order.
 60      * @param left The left index of elements you want to sort in this array
 61      * @param mid The order element separator index
 62      * @param right The right index of elements you want to sort in this array
 63      */
 64     private void merge(int[] haltSortedArr, int[] tmpArr, int left, int mid, int right) {
 65         int i=left;
 66         int j=mid+1;
 67         int d = left;
 68         while (i <= mid && j <= right) {
 69             if (haltSortedArr[i] <= haltSortedArr[j]) {
 70                 tmpArr[d++]=haltSortedArr[i++];
 71             }else{
 72                 tmpArr[d++]=haltSortedArr[j++];
 73             }
 74         }
 75         
 76         if(i>mid){//If i more mid,indicate some elements have not be put in temporary array in array right
 77             while(j<=right){
 78                 tmpArr[d++]=haltSortedArr[j++];
 79             }
 80         }else{//If i less mid,indicate some elements have not be put in temporary array in array left
 81             while(i<=mid){
 82                 tmpArr[d++]=haltSortedArr[i++];
 83             }
 84         }
 85     }
 86     
 87     
 88     /**
 89      * Get a random array by size and max value
 90      * @param size The size the new array you want to create
 91      * @param maxValue The max value in the array;
 92      * @return A randow array
 93      */
 94     private int[] getRandomArray(int size,int maxValue){
 95         int []arr = new int[size];
 96         for(int i=0;i<size;i++){
 97             arr[i]=getIntRandomValue(maxValue);
 98         }
 99         return arr;
100     }
101     
102     /**
103      * Get a random that less than max value
104      * @param maxValue The max value you get the random number
105      * @return A random number less than max value
106      */
107     private int getIntRandomValue(int maxValue){
108         return (int) (Math.random()*maxValue);
109     }
110     
111     
112     /**
113      * This is a method to test how long time the mergeSort spend on
114      * @param arr The array need to sort
115      * @throws Exception
116      */
117     public void testMergeSort(int[] arr) throws Exception{
118         MergeSort m = new MergeSort();
119         Class<?>[] types = {int[].class,int[].class,int.class,int.class};
120         String methodName = "mergeSort";
121         int size = arr.length-1;
122         int[] tmp = new int[size];
123         mergeSort(arr, tmp, 0, size-1);
124         Object[] params={arr,tmp,0,size-1};
125         MethodExecuteTimeUtils.getMethodExecuteTime(m, params,methodName,types,true);
126     }
127     
128     /**
129      * This is a method to test how long time the javaself sort method spend on
130      * @param arr The array need to sort
131      * @throws Exception
132      */
133     public void testJavaSort(int[] arr) throws Exception{
134         Class<?>[] types = {int[].class};
135         String methodName = "sort";
136         Object[] params = {arr};
137         //although Arrays can be instance,you use Arrays.class also available,and static method also available
138         MethodExecuteTimeUtils.getMethodExecuteTime(Arrays.class, params, methodName, types,true);
139     }
140     
141     /**
142      * print array into console
143      * @param arr The array need to print console
144      */
145     public void printArray(int[] arr){
146         System.out.println(Arrays.toString(arr));
147     }
148     
149     /**
150      * This is just a test method
151      * @throws Exception
152      */
153     @Test
154     public void fun3() throws Exception{
155         int size = 922000;
156         int maxValue = 9999999;
157         //construct random array
158         int[] arr1 = getRandomArray(size, maxValue);
159         int[] arr2 = Arrays.copyOf(arr1, size);
160         testMergeSort(arr2);
161         testJavaSort(arr1);
162     }
163     
164     
165     
166     
167 }