如何计算方法在Java中的执行时间?

Ogr*_*m33 792 java timing

如何获得方法的执行时间?是否有Timer实用程序类用于计算任务需要多长时间等等?

Google上的大多数搜索会返回计划线程和任务的计时器的结果,这不是我想要的.

Dia*_*ism 1150

总有一种老式的方式:

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

long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.
Run Code Online (Sandbox Code Playgroud)

  • 实际上,它的"新风格"因为你使用的是nanoTime,直到java5才添加 (223认同)
  • nanoTime并不能保证比currentTimeMillis()更好的准确性,尽管它通常会这样做.http://forums.sun.com/thread.jspa?messageID=9460663和http://www.simongbrown.com/blog/2007/08/20/millisecond_accuracy_in_java.html (18认同)
  • 不需要finally块,因为如果抛出异常,则不会使用endTime. (18认同)
  • 当然,记住微基准测试的缺陷总是很重要的,例如编译器/ JVM优化可能会扭曲结果= 8-) (10认同)
  • 这个(或者使用System.currentTimeMillis())似乎是它通常用Java完成的方式......无论如何我已经看过了.我还是有点不高兴的是,没有漂亮的内置类,比如Timer t = new Timer(); String s = t.getElapsed(format); 等等... (9认同)
  • @JamesSchek小心你的措辞,'nanoTime`保证至少像'currentTimeMillis`一样坚决.http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime%28%29 (6认同)
  • 应该注意的是,“System.currentTimeMillis()”返回操作系统认为自 Unix 纪元以来的时间。如果您的用户(或操作系统本身)在调用“System.currentTimeMillis()”之间更改操作系统时间,那么您可能会得到奇怪的结果。`nanoTime` 不受操作系统时钟时间变化的影响,因此更可靠。 (3认同)
  • @JohnGardner 现在已经过时了。:) (3认同)
  • 请参阅此答案http://stackoverflow.com/a/3383047/870547以Java 8方式完成 (2认同)
  • 作为改进,提取经过的毫秒数的更好方法如下:`double time = (endTime - startTime) * 1e-6;` 它简洁,比除法更快,小数位数明确,并使用“1e-6”文字隐式转换为双精度(请参阅/sf/ask/1086903891/) (2认同)

MBC*_*ook 185

我选择简单的答案.适合我.

long startTime = System.currentTimeMillis();

doReallyLongThing();

long endTime = System.currentTimeMillis();

System.out.println("That took " + (endTime - startTime) + " milliseconds");
Run Code Online (Sandbox Code Playgroud)

它运作得很好.分辨率显然只有毫秒,你可以用System.nanoTime()做得更好.两者都存在一些限制(操作系统计划切片等),但这很有效.

几次运行的平均值(越多越好),你会得到一个不错的主意.

  • 实际上,System.currentTimeMillis()仅在15ms以上准确.对于非常低的值,它不可信任.对此的解决方案(如上所述)是System.nanoTime(); (47认同)
  • @JamesSchek你真的需要注意你的措辞,正如我在其他地方已经提到过这个相同的评论; `nanoTime`保证至少与`currentTimeMillis`一样坚决.http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime%28%29 (5认同)
  • nanoTime()并不能保证精度优于currentTimeMillis,但是许多JVM实现确实具有更好的nanoTime精度. (4认同)

小智 170

拜托了伙计们!没有人提到Guava的方法(这可以说是很棒):

import com.google.common.base.Stopwatch;

Stopwatch timer = Stopwatch.createStarted();
//method invocation
LOG.info("Method took: " + timer.stop());
Run Code Online (Sandbox Code Playgroud)

好的是,Stopwatch.toString()可以很好地选择测量的时间单位.即如果值很小,它将输出38 ns,如果它很长,它将显示5m 3s

更好的:

Stopwatch timer = Stopwatch.createUnstarted();
for (...) {
   timer.start();
   methodToTrackTimeFor();
   timer.stop();
   methodNotToTrackTimeFor();
}
LOG.info("Method took: " + timer);
Run Code Online (Sandbox Code Playgroud)

注意:Google Guava需要Java 1.6+

  • 不幸的是,Guava的秒表不是线程安全的.我经过惨痛的教训才学到这个. (15认同)
  • @DexterLegaspi会对您的体验非常感兴趣!小心分享? (6认同)

Suf*_*ori 133

使用Java 8的新API中的InstantDuration,

Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
Run Code Online (Sandbox Code Playgroud)

输出,

PT5S
Run Code Online (Sandbox Code Playgroud)

  • @ java123999:你可以调用`Duration.between(start,end).getSeconds()`.`Duration`也有转换为其他时间单位的方法,例如`toMillis()`转换为毫秒. (6认同)
  • 谢谢,如何在没有前面的PT的情况下输出结果? (2认同)

Jam*_*hek 85

使用分析器(JProfiler,Netbeans Profiler,Visual VM,Eclipse Profiler等).您将获得最准确的结果,并且是最不具侵入性的.它们使用内置的JVM机制进行性能分析,如果需要,还可以为您提供堆栈跟踪,执行路径和更全面的结果等额外信息.

使用完全集成的分析器时,分析方法很简单.右键单击,Profiler - >添加到根方法.然后像运行测试运行或调试器一样运行探查器.

  • 从java 7 build 40(我认为)他们包括前JRockits Flight Recorder到java(搜索Java Mission Control) (2认同)

Yas*_*ash 85

将所有可能的方式聚集在一起.

日期

Date startDate = Calendar.getInstance().getTime();
long d_StartTime = new Date().getTime();
Thread.sleep(1000 * 4);
Date endDate = Calendar.getInstance().getTime();
long d_endTime = new Date().getTime();
System.out.format("StartDate : %s, EndDate : %s \n", startDate, endDate);
System.out.format("Milli = %s, ( D_Start : %s, D_End : %s ) \n", (d_endTime - d_StartTime),d_StartTime, d_endTime);
Run Code Online (Sandbox Code Playgroud)

系统.的currentTimeMillis()

long startTime = System.currentTimeMillis();
Thread.sleep(1000 * 4);
long endTime = System.currentTimeMillis();
long duration = (endTime - startTime);  
System.out.format("Milli = %s, ( S_Start : %s, S_End : %s ) \n", duration, startTime, endTime );
System.out.println("Human-Readable format : "+millisToShortDHMS( duration ) );
Run Code Online (Sandbox Code Playgroud)

人类可读格式

public static String millisToShortDHMS(long duration) {
    String res = "";    // java.util.concurrent.TimeUnit;
    long days       = TimeUnit.MILLISECONDS.toDays(duration);
    long hours      = TimeUnit.MILLISECONDS.toHours(duration) -
                      TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
    long minutes    = TimeUnit.MILLISECONDS.toMinutes(duration) -
                      TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
    long seconds    = TimeUnit.MILLISECONDS.toSeconds(duration) -
                      TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
    long millis     = TimeUnit.MILLISECONDS.toMillis(duration) - 
                      TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(duration));

    if (days == 0)      res = String.format("%02d:%02d:%02d.%04d", hours, minutes, seconds, millis);
    else                res = String.format("%dd %02d:%02d:%02d.%04d", days, hours, minutes, seconds, millis);
    return res;
}
Run Code Online (Sandbox Code Playgroud)

番石榴:谷歌 秒表JAR « 秒表的一个目标是测量经过的时间,以纳秒为单位.

com.google.common.base.Stopwatch g_SW = Stopwatch.createUnstarted();
g_SW.start();
Thread.sleep(1000 * 4);
g_SW.stop();
System.out.println("Google StopWatch  : "+g_SW);
Run Code Online (Sandbox Code Playgroud)

Apache Commons Lang JAR « StopWatch为时序提供了一个方便的API.

org.apache.commons.lang3.time.StopWatch sw = new StopWatch();
sw.start();     
Thread.sleep(1000 * 4);     
sw.stop();
System.out.println("Apache StopWatch  : "+ millisToShortDHMS(sw.getTime()) );
Run Code Online (Sandbox Code Playgroud)

JODA -TIME

public static void jodaTime() throws InterruptedException, ParseException{
    java.text.SimpleDateFormat ms_SDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    String start = ms_SDF.format( new Date() ); // java.util.Date

    Thread.sleep(10000);

    String end = ms_SDF.format( new Date() );       
    System.out.println("Start:"+start+"\t Stop:"+end);

    Date date_1 = ms_SDF.parse(start);
    Date date_2 = ms_SDF.parse(end);        
    Interval interval = new org.joda.time.Interval( date_1.getTime(), date_2.getTime() );
    Period period = interval.toPeriod(); //org.joda.time.Period

    System.out.format("%dY/%dM/%dD, %02d:%02d:%02d.%04d \n", 
        period.getYears(), period.getMonths(), period.getDays(),
        period.getHours(), period.getMinutes(), period.getSeconds(), period.getMillis());
}
Run Code Online (Sandbox Code Playgroud)

来自Java 8的Java日期时间API « 持续时间对象表示两个Instant对象之间的时间段.

Instant start = java.time.Instant.now();
    Thread.sleep(1000);
Instant end = java.time.Instant.now();
Duration between = java.time.Duration.between(start, end);
System.out.println( between ); // PT1.001S
System.out.format("%dD, %02d:%02d:%02d.%04d \n", between.toDays(),
        between.toHours(), between.toMinutes(), between.getSeconds(), between.toMillis()); // 0D, 00:00:01.1001 
Run Code Online (Sandbox Code Playgroud)

Spring Framework提供了 StopWatch实用程序类来测量Java中的已用时间.

StopWatch sw = new org.springframework.util.StopWatch();
sw.start("Method-1"); // Start a named task
    Thread.sleep(500);
sw.stop();

sw.start("Method-2");
    Thread.sleep(300);
sw.stop();

sw.start("Method-3");
    Thread.sleep(200);
sw.stop();

System.out.println("Total time in milliseconds for all tasks :\n"+sw.getTotalTimeMillis());
System.out.println("Table describing all tasks performed :\n"+sw.prettyPrint());

System.out.format("Time taken by the last task : [%s]:[%d]", 
        sw.getLastTaskName(),sw.getLastTaskTimeMillis());

System.out.println("\n Array of the data for tasks performed « Task Name: Time Taken");
TaskInfo[] listofTasks = sw.getTaskInfo();
for (TaskInfo task : listofTasks) {
    System.out.format("[%s]:[%d]\n", 
            task.getTaskName(), task.getTimeMillis());
}
Run Code Online (Sandbox Code Playgroud)

输出:

Total time in milliseconds for all tasks :
999
Table describing all tasks performed :
StopWatch '': running time (millis) = 999
-----------------------------------------
ms     %     Task name
-----------------------------------------
00500  050%  Method-1
00299  030%  Method-2
00200  020%  Method-3

Time taken by the last task : [Method-3]:[200]
 Array of the data for tasks performed « Task Name: Time Taken
[Method-1]:[500]
[Method-2]:[299]
[Method-3]:[200]
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,如果每个解决方案都能显示系统输出的输出,那么这篇文章将会受益匪浅。 (2认同)

ska*_*man 38

这可能不是你想要我说的,但这是AOP的一个很好的用法.在你的方法周围打一个代理拦截器,并在那里做时间.

可悲的是,AOP的内容,原因和方式超出了这个答案的范围,但这就是我可能做到的.

编辑:如果您热衷于此,这里有一个指向 Spring AOP 的链接,可以帮助您入门.这是Iive最容易实现的AOP实现.

另外,鉴于其他人的非常简单的建议,我应该补充一点,AOP适用于你不想要时间来侵入代码的东西.但在许多情况下,这种简单易行的方法很好.

  • 以下是有关如何使用Spring执行此操作的教程:http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/ (3认同)

Ton*_*CZE 37

System.currentTimeMillis();这不是衡量算法性能的好方法.它衡量用户观看计算机屏幕时的总体时间.它还包括在后台运行在计算机上的所有其他内容所消耗的时间.如果您的工作站上运行了很多程序,这可能会产生巨大的差异.

正确的方法是使用java.lang.management包.

来自http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking网站:

  • "用户时间"是运行应用程序自己的代码所花费的时间.
  • "系统时间"是代表您的应用程序运行OS代码所花费的时间(例如I/O).

getCpuTime() 方法给你的总和:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class CPUUtils {

    /** Get CPU time in nanoseconds. */
    public static long getCpuTime( ) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
        return bean.isCurrentThreadCpuTimeSupported( ) ?
            bean.getCurrentThreadCpuTime( ) : 0L;
    }

    /** Get user time in nanoseconds. */
    public static long getUserTime( ) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
        return bean.isCurrentThreadCpuTimeSupported( ) ?
            bean.getCurrentThreadUserTime( ) : 0L;
    }

    /** Get system time in nanoseconds. */
    public static long getSystemTime( ) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
        return bean.isCurrentThreadCpuTimeSupported( ) ?
            (bean.getCurrentThreadCpuTime( ) - bean.getCurrentThreadUserTime( )) : 0L;
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 这绝对是一个好点,"用户时间"(挂钟时间)并不总是很好的衡量,特别是在多线程程序中. (3认同)

Ste*_*fan 26

使用Java 8,您可以使用每种常规方法执行类似的操作:

Object returnValue = TimeIt.printTime(() -> methodeWithReturnValue());
//do stuff with your returnValue
Run Code Online (Sandbox Code Playgroud)

与TimeIt像:

public class TimeIt {

public static <T> T printTime(Callable<T> 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;
}
}
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您可以在代码中的任何位置轻松进行时间测量而不会破坏它.在这个简单的例子中,我只打印时间.你可以为TimeIt添加一个Switch,例如只在DebugMode中打印时间.

如果你正在使用Function,你可以做这样的事情:

Function<Integer, Integer> 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 <T, R> Function<T, R> printTime2(Function<T, R> task) {
    return (t) -> {
        long startTime = System.currentTimeMillis();
        R apply = task.apply(t);
        System.out.print((System.currentTimeMillis() - startTime) / 1000d
                + "s");
        return apply;
    };
}
Run Code Online (Sandbox Code Playgroud)


小智 17

我们也可以使用Apache公共的StopWatch类来测量时间.

示例代码

org.apache.commons.lang.time.StopWatch sw = new org.apache.commons.lang.time.StopWatch();

System.out.println("getEventFilterTreeData :: Start Time : " + sw.getTime());
sw.start();

// Method execution code

sw.stop();
System.out.println("getEventFilterTreeData :: End Time : " + sw.getTime());
Run Code Online (Sandbox Code Playgroud)


Han*_*örr 15

如果你不使用工具并且想要以低执行时间计时方法,那么只需要很小的一点:执行它多次,每次执行的次数加倍,直到你达到一秒左右.因此,调用System.nanoTime等的时间,以及System.nanoTime的准确性确实会对结果产生很大影响.

    int runs = 0, runsPerRound = 10;
    long begin = System.nanoTime(), end;
    do {
        for (int i=0; i<runsPerRound; ++i) timedMethod();
        end = System.nanoTime();
        runs += runsPerRound;
        runsPerRound *= 2;
    } while (runs < Integer.MAX_VALUE / 2 && 1000000000L > end - begin);
    System.out.println("Time for timedMethod() is " + 
        0.000000001 * (end-begin) / runs + " seconds");
Run Code Online (Sandbox Code Playgroud)

当然,关于使用挂钟的注意事项适用:JIT编译的影响,多线程/进程等.因此,您需要首先执行该方法很多次,这样JIT编译器才能完成其工作,然后多次重复此测试并执行最短的执行时间.


小智 13

我们正在使用AspectJ和Java注释来实现此目的.如果我们需要了解方法的执行时间,我们可以简单地注释它.更高级的版本可以使用可在运行时启用和禁用的自己的日志级别.

public @interface Trace {
  boolean showParameters();
}

@Aspect
public class TraceAspect {
  [...]
  @Around("tracePointcut() && @annotation(trace) && !within(TraceAspect)")
  public Object traceAdvice ( ProceedingJintPoint jP, Trace trace ) {

    Object result;
    // initilize timer

    try { 
      result = jp.procced();
    } finally { 
      // calculate execution time 
    }

    return result;
  }
  [...]
}
Run Code Online (Sandbox Code Playgroud)


ice*_*erg 11

真的很好的代码.

http://www.rgagnon.com/javadetails/java-0585.html

import java.util.concurrent.TimeUnit;

long startTime = System.currentTimeMillis();
........
........
........
long finishTime = System.currentTimeMillis();

String diff = millisToShortDHMS(finishTime - startTime);


  /**
   * converts time (in milliseconds) to human-readable format
   *  "<dd:>hh:mm:ss"
   */
  public static String millisToShortDHMS(long duration) {
    String res = "";
    long days  = TimeUnit.MILLISECONDS.toDays(duration);
    long hours = TimeUnit.MILLISECONDS.toHours(duration)
                   - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
                     - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
                   - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
    if (days == 0) {
      res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
    else {
      res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
    }
    return res;
  }
Run Code Online (Sandbox Code Playgroud)

  • 实际上问题是如何计算方法所花费的时间,而不是如何格式化它.然而这个问题已经很久了(差不多四年了!).尽量避免重新使用旧线程,除非响应会在现有响应中添加新的重要内容. (3认同)

Bas*_*que 11

JEP 230:Microbenchmark Suite

仅供参考,JEP 230:Microbenchmark Suite是一项OpenJDK提案,旨在:

在JDK源代码中添加一套基本的微基准测试,使开发人员可以轻松运行现有的微基准测试并创建新的基准测试.

这个提议没有为Java 9做好准备,但可能会在以后添加.

Java Microbenchmark线束(JMH)

与此同时,您可能需要查看提案所基于的Java Microbenchmark Harness(JMH)项目.


mer*_*hik 10

你可以使用Perf4j.很酷的实用程序.用法很简单

String watchTag = "target.SomeMethod";
StopWatch stopWatch = new LoggingStopWatch(watchTag);
Result result = null; // Result is a type of a return value of a method
try {
    result = target.SomeMethod();
    stopWatch.stop(watchTag + ".success");
} catch (Exception e) {
    stopWatch.stop(watchTag + ".fail", "Exception was " + e);
    throw e; 
}
Run Code Online (Sandbox Code Playgroud)

更多信息可以在开发人员指南中找到

编辑:项目似乎已经死了


Bha*_*ani 10

在 Spring 框架中,我们有一个名为 StopWatch 的调用(org.springframework.util.StopWatch)

//measuring elapsed time using Spring StopWatch
        StopWatch watch = new StopWatch();
        watch.start();
        for(int i=0; i< 1000; i++){
            Object obj = new Object();
        }
        watch.stop();
        System.out.println("Total execution time to create 1000 objects in Java using StopWatch in millis: "
                + watch.getTotalTimeMillis());
Run Code Online (Sandbox Code Playgroud)


Mac*_*eft 8

new Timer(""){{
    // code to time 
}}.timeMe();



public class Timer {

    private final String timerName;
    private long started;

    public Timer(String timerName) {
        this.timerName = timerName;
        this.started = System.currentTimeMillis();
    }

    public void timeMe() {
        System.out.println(
        String.format("Execution of '%s' takes %dms.", 
                timerName, 
                started-System.currentTimeMillis()));
    }

}
Run Code Online (Sandbox Code Playgroud)


luk*_*uke 7

我基本上做了这方面的变化,但考虑到热点编译的工作原理,如果你想获得准确的结果,你需要抛出前几个测量并确保你在现实世界中使用该方法(特定于应用程序)应用程序.

如果JIT决定编译它,你的数字会有很大差异.所以请注意


yeg*_*256 7

使用@Loggable来自jcabi-aspects的 AOP/AspectJ和注释,您可以轻松简洁地完成:

@Loggable(Loggable.DEBUG)
public String getSomeResult() {
  // return some value
}
Run Code Online (Sandbox Code Playgroud)

每次调用此方法都将发送到具有DEBUG日志记录级别的SLF4J日志记录工具.每条日志消息都包含执行时间.


Hor*_*ann 6

有几种方法可以做到这一点.我通常会回到使用这样的东西:

long start = System.currentTimeMillis();
// ... do something ...
long end = System.currentTimeMillis();
Run Code Online (Sandbox Code Playgroud)

与System.nanoTime()相同的事情;

对于基准测试方面的更多内容,似乎还有这个:http://jetm.void.fm/从未尝试过.


Sun*_*eri 6

根据JavaDoc,Spring提供了一个实用程序类org.springframework.util.StopWatch

简单的秒表,允许为多个任务计时,公开总运行时间和每个命名任务的运行时间。

用法:

StopWatch stopWatch = new StopWatch("Performance Test Result");

stopWatch.start("Method 1");
doSomething1();//method to test
stopWatch.stop();

stopWatch.start("Method 2");
doSomething2();//method to test
stopWatch.stop();

System.out.println(stopWatch.prettyPrint());
Run Code Online (Sandbox Code Playgroud)

输出:

StopWatch 'Performance Test Result': running time (millis) = 12829
-----------------------------------------
ms     %     Task name
-----------------------------------------
11907  036%  Method 1
00922  064%  Method 2
Run Code Online (Sandbox Code Playgroud)

与方面:

@Around("execution(* my.package..*.*(..))")
public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Object retVal = joinPoint.proceed();
    stopWatch.stop();
    log.info(" execution time: " + stopWatch.getTotalTimeMillis() + " ms");
    return retVal;
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*til 6

我已经编写了一种方法,以一种易于阅读的形式打印该方法的执行时间。例如,要计算100万的阶乘,大约需要9分钟。因此执行时间被打印为:

Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds
Run Code Online (Sandbox Code Playgroud)

代码在这里:

public class series
{
    public static void main(String[] args)
    {
        long startTime = System.nanoTime();

        long n = 10_00_000;
        printFactorial(n);

        long endTime = System.nanoTime();
        printExecutionTime(startTime, endTime);

    }

    public static void printExecutionTime(long startTime, long endTime)
    {
        long time_ns = endTime - startTime;
        long time_ms = TimeUnit.NANOSECONDS.toMillis(time_ns);
        long time_sec = TimeUnit.NANOSECONDS.toSeconds(time_ns);
        long time_min = TimeUnit.NANOSECONDS.toMinutes(time_ns);
        long time_hour = TimeUnit.NANOSECONDS.toHours(time_ns);

        System.out.print("\nExecution Time: ");
        if(time_hour > 0)
            System.out.print(time_hour + " Hours, ");
        if(time_min > 0)
            System.out.print(time_min % 60 + " Minutes, ");
        if(time_sec > 0)
            System.out.print(time_sec % 60 + " Seconds, ");
        if(time_ms > 0)
            System.out.print(time_ms % 1E+3 + " MicroSeconds, ");
        if(time_ns > 0)
            System.out.print(time_ns % 1E+6 + " NanoSeconds");
    }
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*hme 5

如果您想要挂钟时间

long start_time = System.currentTimeMillis();
object.method();
long end_time = System.currentTimeMillis();
long execution_time = end_time - start_time;
Run Code Online (Sandbox Code Playgroud)


Rya*_*yer 5

long startTime = System.currentTimeMillis();
// code goes here
long finishTime = System.currentTimeMillis();
long elapsedTime = finishTime - startTime; // elapsed time in milliseconds
Run Code Online (Sandbox Code Playgroud)


anj*_*anb 5

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

您可以查看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

如果您最终设法按照自己的意愿去做,请。与您的蚂蚁任务/罐子在这里与社区共享。


Jus*_*tas 5

您可以使用提供各种测量仪器的Metrics库。添加依赖项:

<dependencies>
    <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-core</artifactId>
        <version>${metrics.version}</version>
    </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

并根据您的环境进行配置。

可以使用@Timed注释方法:

@Timed
public void exampleMethod(){
    // some code
}
Run Code Online (Sandbox Code Playgroud)

或用Timer包装的一段代码:

final Timer timer = metricsRegistry.timer("some_name");
final Timer.Context context = timer.time();
// timed code
context.stop();
Run Code Online (Sandbox Code Playgroud)

汇总指标可以导出到控制台,JMX,CSV或其他。

@Timed 指标输出示例:

com.example.ExampleService.exampleMethod
             count = 2
         mean rate = 3.11 calls/minute
     1-minute rate = 0.96 calls/minute
     5-minute rate = 0.20 calls/minute
    15-minute rate = 0.07 calls/minute
               min = 17.01 milliseconds
               max = 1006.68 milliseconds
              mean = 511.84 milliseconds
            stddev = 699.80 milliseconds
            median = 511.84 milliseconds
              75% <= 1006.68 milliseconds
              95% <= 1006.68 milliseconds
              98% <= 1006.68 milliseconds
              99% <= 1006.68 milliseconds
            99.9% <= 1006.68 milliseconds
Run Code Online (Sandbox Code Playgroud)