How do I time a method's execution in Java?

前端 未结 30 2697
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

30条回答
  •  野的像风
    2020-11-21 11:39

    With Java 8 you can do also something like this with every normal methods:

    Object returnValue = TimeIt.printTime(() -> methodeWithReturnValue());
    //do stuff with your returnValue
    

    with TimeIt like:

    public class TimeIt {
    
    public static  T printTime(Callable task) {
        T call = null;
        try {
            long startTime = System.currentTimeMillis();
            call = task.call();
            System.out.print((System.currentTimeMillis() - startTime) / 1000d + "s");
        } catch (Exception e) {
            //...
        }
        return call;
    }
    }
    

    With this methode you can make easy time measurement anywhere in your code without breaking it. In this simple example i just print the time. May you add a Switch for TimeIt, e.g. to only print the time in DebugMode or something.

    If you are working with Function you can do somthing like this:

    Function yourFunction= (n) -> {
            return IntStream.range(0, n).reduce(0, (a, b) -> a + b);
        };
    
    Integer returnValue = TimeIt.printTime2(yourFunction).apply(10000);
    //do stuff with your returnValue
    
    public static  Function printTime2(Function task) {
        return (t) -> {
            long startTime = System.currentTimeMillis();
            R apply = task.apply(t);
            System.out.print((System.currentTimeMillis() - startTime) / 1000d
                    + "s");
            return apply;
        };
    }
    

提交回复
热议问题