Java에서 메소드 실행 시간을 어떻게 설정합니까? Timer작업 소요 시간 등 의

  1. 메소드의 실행 시간은 어떻게 얻습니까?
  2. Timer작업 소요 시간 등 의 유틸리티 클래스가 있습니까?

Google 검색의 대부분은 스레드와 작업을 예약하는 타이머에 대한 결과를 반환하지만 이는 내가 원하는 것이 아닙니다.



답변

항상 구식 방법이 있습니다.

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

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

답변

나는 간단한 대답으로 간다. 나를 위해 작동합니다.

long startTime = System.currentTimeMillis();

doReallyLongThing();

long endTime = System.currentTimeMillis();

System.out.println("That took " + (endTime - startTime) + " milliseconds");

꽤 잘 작동합니다. 해결 방법은 밀리 초에 불과하며 System.nanoTime ()으로 더 잘 수행 할 수 있습니다. 운영 체제 일정 조각 등에는 두 가지 제한 사항이 있지만 이것은 잘 작동합니다.

두 번의 런을 평균하면 (더 좋을수록) 괜찮은 아이디어를 얻게됩니다.


답변

얘들 아! 아무도 구아바의 방법을 언급 하지 않았습니다 (아마도 굉장합니다) :

import com.google.common.base.Stopwatch;

Stopwatch timer = Stopwatch.createStarted();
//method invocation
LOG.info("Method took: " + timer.stop());

좋은 점은 Stopwatch.toString ()이 측정 할 시간 단위를 선택하는 것입니다. 즉, 값이 작 으면 38ns를 출력하고, 길면 5m 3을 표시합니다

더 좋은 :

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

참고 : Google Guava에는 Java 1.6 이상이 필요합니다


답변

Java 8의 새로운 API에서 Instant and Duration 을 사용하여

Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));

출력,

PT5S

답변

가능한 모든 방법을 한 곳에 모았습니다.

데이트

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);

체계. 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 ) );

인간이 읽을 수있는 형식

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;
}

구아바 : 구글 스톱워치 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);

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()) );

요다 시간

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());
}

Java 8의 Java 날짜 시간 API « Duration 객체는 두 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 

Spring Framework 는Java에서 경과 시간을 측정하기 위해 StopWatch 유틸리티 클래스를제공합니다.

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());
}

산출:

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]

답변

프로파일 러 (JProfiler, Netbeans Profiler, Visual VM, Eclipse Profiler 등)를 사용하십시오. 가장 정확한 결과를 얻을 수 있으며 가장 방해가되지 않습니다. 프로파일 링에 내장 된 JVM 메커니즘을 사용하여 스택 추적, 실행 경로 및 필요한 경우보다 포괄적 인 결과와 같은 추가 정보를 제공 할 수 있습니다.

완전히 통합 된 프로파일 러를 사용하는 경우 분석법 프로파일 링이 쉽지 않습니다. 프로파일 러-> 루트 메소드에 추가를 마우스 오른쪽 단추로 클릭하십시오. 그런 다음 테스트 실행 또는 디버거를 수행하는 것처럼 프로파일 러를 실행하십시오.


답변

이것은 아마 당신이 말하고 싶지 않은 것이지만 이것은 AOP를 잘 사용하는 것입니다. 메소드 주변에 프록시 인터셉터를 채운 후 타이밍을 수행하십시오.

AOP의 대상, 이유 및 방법은 슬프게도이 답변의 범위를 벗어나지 만, 그렇게 할 가능성이 있습니다.

편집 : 여기에 관심이 있다면 Spring AOP에 대한 링크 가 있습니다. 이것은 Iive가 java를 위해 제공하는 가장 액세스 가능한 AOP 구현입니다.

또한 다른 모든 사람들의 매우 간단한 제안을 고려할 때 AOP는 코드에 침입하는 타이밍과 같은 것을 원하지 않을 때를 위해 추가해야합니다. 그러나 많은 경우에 이러한 종류의 간단하고 쉬운 접근 방식이 좋습니다.