A tool class that calculates the execution time of any method in Java __java

Source: Internet
Author: User

How to get the execution time of a method, whether it is a static method or a static method, whether it is a private method or a common method, if the object cannot be

is instantiated and can be used with the object's class object, for example, Arrays.class can also be passed into the method as a bean

You can use beans and bean.class only if the method is static, but if it's not static, you use Bean.class to make an error.

This method is mainly used to calculate the execution time of a method and whether to print the method of the execution time and output results, I made this method is mainly used to compare the time complexity of the sorting algorithm

The following is the code for the tool class:

Package algorithm.study.utils;

Import Java.lang.reflect.Method;
 /** * This class is getting a to execute time and provide some the other functions. * * @author Ygh February 24, 2017/public class Methodexecutetimeutils {/** * get A to execute time using mil
     Lisecond and Cancel method ' s print return result and * Execute time. * * @param bean the ' method ' in this bean * @param params The parameter the ' method execute need * @param MethodName the ' method * @param types The parameter type of the ' method * @return ' Execute time of
     This method * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail.
            */public static long Getmethodexecutetime (Object bean, object[] params, String methodname, class<?>[] types)
    Throws Exception {return getmethodexecutetime (bean, params, methodname, types, false, false); }/** * Get A is execute time Using millisecond and cancel Print method. * * @param bean the ' method ' in this bean * @param params The parameter the ' method execute need * @param MethodName the name of the method * @param types The parameter type of the @param isprintexecutetime Wh  Ether Print the Execute time in console, true is print false not * @param isviewmehtodresult Whether Print Result in console, true is print false not * @return The Execute time of this method * @throws Exception If
     ;code>getmethod</code> or <code>invoke</code> fail. */public static long Getmethodexecutetime (Object bean, object[] params, String methodname, class<?> [] Types, Boolean isprintexecutetime) throws Exception {return getmethodexecutetime (bean, params, methodname, Typ
    Es, Isprintexecutetime, false); }/** * Get A is execute time using millisecond and add some the other service.
     * * @param bean the ' method ' in this bean * @param params The parameter the ' method execute need * @ Param methodname The name of the method * @param types The parameter type of the @param isprintexecutet IME Whether Print the Execute time in console, true is print false not * @param isviewmehtodresult Whether Print Return result in console, true is print false not * @return The ' execute time ' of this method * @throws Exception
     If <code>getMethod</code> or <code>invoke</code> fail. */public static long Getmethodexecutetime (Object bean, object[] params, String methodname, class<?>
        [] Types, Boolean isprintexecutetime, Boolean Isviewmehtodresult) throws Exception {class<?> clazz;
        Long executetime = -1l;
        Boolean isaccessiable = false;
        Method method = null;
 if (bean instanceof class<?>) {clazz = (class<?>) bean;       else {clazz = Bean.getclass ();
            try {if (types = = null) {method = Clazz.getdeclaredmethod (methodname);
            else {method = Clazz.getdeclaredmethod (methodname, types);
            } isaccessiable = Method.isaccessible ();
            if (!isaccessiable) {method.setaccessible (true);
            } if (isviewmehtodresult) {executetime = Getreturnmethodexecutetime (bean, params, method);
            else {executetime = Getmethodexecutetime (bean, params, method);
            } method.setaccessible (isaccessiable);
            if (isprintexecutetime) {Printexecute (Clazz, MethodName, Executetime);
        The catch (Exception e) {throw new Exception ("Excute method fail");
    return executetime; /** * Get A is execute time and use millisecond. We don ' t do whether has a return * result * * @param bean the "is" in this bean * @param params The parameters the method execute need * @param method entity * @return The Millisecon D The method execute spend * @throws Exception If The method invoke fail/private static long Getmethodexe Cutetime (Object Bean, object[] params, method method) throws Exception {Long starttime = System.currenttimemillis
        ();
        Method.invoke (bean, params);
        Long endtime = System.currenttimemillis ();
    return endtime-starttime; /** * Get A is execute time and use millisecond. The method must has a return to result would input * The return result in console, If the method has not return result, p
     Lease Call * <code>getMethodExecuteTime</code> method. * * @param bean the ' method ' in this bean * @param params The Parameters the ' method execute need * @paRam Method Entity * @return The millisecond the "method execute spend * @throws Exception If the Metho
            D Invoke fail */private static long Getreturnmethodexecutetime (Object bean, object[] params, method method)
        Throws Exception {Long starttime = System.currenttimemillis ();
        Object result = (object) method.invoke (bean, params);
        Long endtime = System.currenttimemillis ();
        if (result!= null) {System.out.println ("result input:" + result.tostring ());
                    else {System.out.println ("Warning:" + bean.getclass (). GetName () + "." + Method.getname ()
        + "has not return" + "result,please setting the Isviewmehtodresult as false");
    return endtime-starttime; /** * Print The Execute time of method * * @param methodname the name of the ' method * @param t IME the Execute of the method */public static void Printexecute (class<? > Clazz, String methodname, long time} {System.out.println (Clazz.getname () + "." + methodname + "Execute time
    : "+ time); }
}

Test code


public class Reflecttest {
@Test
public void Fun1 () throws Exception {
person who = new person ();
object[] params = null;
class<?>[] types = null;
Methodexecutetimeutils.getmethodexecutetime (person, params, "fun2", types, True, true);
}
@Test
public void Fun2 () throws Exception {
person who = new person ();
object[] params = null;
class<?>[] types = null;
Methodexecutetimeutils.getmethodexecutetime (person, params, "fun1", types, True, true);
}
@Test
public void Fun3 () throws Exception {
person who = new person ();
Object[] params = {12};
Class<?>[] types = {Integer.class};
Methodexecutetimeutils.getmethodexecutetime (person, params, "setage", types, True, true);
System.out.println (Person.getage ());
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.