如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?

在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。


当前回答

在java ee中对我有效的策略是:

Create a class with a method annotated with @AroundInvoke; @Singleton public class TimedInterceptor implements Serializable { @AroundInvoke public Object logMethod(InvocationContext ic) throws Exception { Date start = new Date(); Object result = ic.proceed(); Date end = new Date(); System.out.println("time: " + (end.getTime - start.getTime())); return result; } } Annotate the method that you want to monitoring: @Interceptors(TimedInterceptor.class) public void onMessage(final Message message) { ...

我希望这能有所帮助。

其他回答

也可以实现定时器接口,并在类的任何方法上执行

import java.util.function.*;

public interface Timer {

    default void timeIt(Runnable r) {
        timeIt(() -> { r.run(); return 0;});
    }

    default <S,T> T timeIt(Function<S,T> fun, S arg) {
        long start = System.nanoTime();
        T result = fun.apply(arg);
        long stop = System.nanoTime();
        System.out.println("Time: " + (stop-start)/1000000.0 + " msec");
        return result;
    }

    default <T> T timeIt(Supplier<T> s) {
        return timeIt(obj -> s.get(), null);
    }
}

用法:

class MyClass implements Timer ..

timeIt(this::myFunction); 

总有一些过时的方法:

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.

正如“skaffman”所说,使用AOP或您可以使用运行时字节码编织,就像使用单元测试方法覆盖工具透明地向调用的方法添加计时信息一样。

您可以查看开源工具(如Emma (http://downloads.sourceforge.net/emma/emma-2.0.5312-src.zip?modtime=1118607545&big_mirror=0))使用的代码。另一个开源覆盖工具是http://prdownloads.sourceforge.net/cobertura/cobertura-1.9-src.zip?download。

如果你最终做到了你所设定的目标,请用你的ant task/jars与社区分享。

在Java 8中引入了一个名为Instant的新类。根据文件:

Instant represents the start of a nanosecond on the time line. This class is useful for generating a time stamp to represent machine time. The range of an instant requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999. The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z where instants after the epoch have positive values, and earlier instants have negative values. For both the epoch-second and nanosecond parts, a larger value is always later on the time-line than a smaller value.

这可以用于:

Instant start = Instant.now();
try {
    Thread.sleep(7000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
Instant end = Instant.now();
System.out.println(Duration.between(start, end));

打印pt7.001。

如果java有更好的功能支持就好了,这样需要测量的动作就可以被包装到一个块中:

measure {
   // your operation here
}

在java中,这可以通过匿名函数来完成,看起来太冗长了

public interface Timer {
    void wrap();
}


public class Logger {

    public static void logTime(Timer timer) {
        long start = System.currentTimeMillis();
        timer.wrap();
        System.out.println("" + (System.currentTimeMillis() - start) + "ms");
    }

    public static void main(String a[]) {
        Logger.logTime(new Timer() {
            public void wrap() {
                // Your method here
                timeConsumingOperation();
            }
        });

    }

    public static void timeConsumingOperation() {
        for (int i = 0; i<=10000; i++) {
           System.out.println("i=" +i);
        }
    }
}