Java에서 메소드 실행 시간을 어떻게 측정합니까?
메서드의 실행 시간은 어떻게 얻습니까? 작업에 걸리는 시간 등의 타이밍에 대한 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 3s를 표시합니다.
더 좋게 :
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 및 Duration 사용 ,
Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
출력,
PT5S
프로파일 러 (JProfiler, Netbeans Profiler, Visual VM, Eclipse Profiler 등)를 사용합니다. 가장 정확한 결과를 얻을 수 있으며 방해가 적습니다. 프로파일 링을 위해 내장 된 JVM 메커니즘을 사용하여 스택 추적, 실행 경로 및 필요한 경우보다 포괄적 인 결과와 같은 추가 정보를 제공 할 수도 있습니다.
완전히 통합 된 프로파일 러를 사용할 때 메서드를 프로파일 링하는 것은 쉽지 않습니다. Profiler-> Add to Root Methods를 마우스 오른쪽 버튼으로 클릭합니다. 그런 다음 테스트 실행 또는 디버거를 수행하는 것처럼 프로파일 러를 실행합니다.
가능한 모든 방법을 한 곳에 모았습니다.
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);
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;
}
Guava : Google Stopwatch JAR « Stopwatch 의 목적은 경과 시간을 나노초 단위로 측정하는 것입니다.
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()) );
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());
}
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]
이것은 아마도 당신이 말하고 싶은 것이 아니지만 이것은 AOP의 좋은 사용입니다. 메서드 주변에 프록시 인터셉터를 휘두르고 거기에서 타이밍을 조정하십시오.
AOP의 내용, 이유 및 방법은 슬프게도이 답변의 범위를 벗어 났지만 그렇게 할 가능성이 높습니다.
편집 : 열심 인 경우 시작하는 데 도움이되는 Spring AOP 링크 가 있습니다. 이것은 Iive가 Java에서 접하는 AOP의 가장 접근하기 쉬운 구현입니다.
또한 다른 모든 사람들의 매우 간단한 제안을 감안할 때 AOP는 타이밍과 같은 것들이 코드를 침범하지 않기를 원할 때를위한 것임을 추가해야합니다. 그러나 많은 경우에 이러한 종류의 간단하고 쉬운 접근 방식은 괜찮습니다.
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;
}
}
Java 8을 사용하면 모든 일반 메서드에서 다음 과 같은 작업을 수행 할 수도 있습니다 .
Object returnValue = TimeIt.printTime(() -> methodeWithReturnValue());
//do stuff with your returnValue
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;
}
}
이 방법을 사용하면 코드를 깨지 않고 어디서나 쉽게 시간을 측정 할 수 있습니다. 이 간단한 예에서는 시간을 인쇄합니다. TimeIt에 대한 스위치를 추가 할 수 있습니다. 예를 들어 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;
};
}
또한 시간을 측정하기 위해 Apache commons의 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());
도구를 사용하지 않고 실행 시간이 짧은 메소드의 시간을 측정하려는 경우 약간의 비틀기입니다. 여러 번 실행하고 1 초에 도달 할 때까지 실행되는 횟수를 두 배로 늘립니다. 따라서 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");
물론 벽시계 사용에 대한주의 사항이 적용됩니다 : JIT 컴파일의 영향, 다중 스레드 / 프로세스 등. 따라서 먼저 메서드 를 여러 번 실행 하여 JIT 컴파일러가 작업을 수행 한 다음 이 테스트를 여러 번 반복하고 실행 시간을 최소화하십시오.
이를 위해 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;
}
[...]
}
정말 좋은 코드입니다.
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;
}
JEP 230 : Microbenchmark 제품군
FYI, JEP 230 : Microbenchmark Suite 는 다음을위한 OpenJDK 프로젝트입니다.
JDK 소스 코드에 기본 마이크로 벤치 마크 제품군을 추가하면 개발자가 기존 마이크로 벤치 마크를 쉽게 실행하고 새 마이크로 벤치 마크를 만들 수 있습니다.
이 기능은 Java 12에 도입되었습니다 .
JMH (Java Microbenchmark Harness)
이전 버전의 Java의 경우 JEP 230의 기반이되는 JMH (Java Microbenchmark Harness) 프로젝트를 살펴보십시오 .
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;
}
자세한 내용은 개발자 가이드 에서 찾을 수 있습니다.
편집 : 프로젝트가 죽은 것 같습니다
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()));
}
}
나는 기본적으로 이것의 변형을 수행하지만 핫스팟 컴파일이 작동하는 방식을 고려할 때 정확한 결과를 얻으려면 처음 몇 가지 측정을 버리고 실제 (응용 프로그램 읽기) 응용 프로그램에서 메서드를 사용하고 있는지 확인해야합니다.
JIT가 컴파일하기로 결정하면 숫자가 크게 달라집니다. 그러니 조심하세요
AOP / AspectJ 및 jcabi-aspects의@Loggable
주석을 사용 하면 쉽고 간단하게 수행 할 수 있습니다.
@Loggable(Loggable.DEBUG)
public String getSomeResult() {
// return some value
}
이 메소드에 대한 모든 호출은 DEBUG
로깅 수준 과 함께 SLF4J 로깅 기능으로 전송됩니다 . 그리고 모든 로그 메시지에는 실행 시간이 포함됩니다.
이를 수행하는 몇 가지 방법이 있습니다. 나는 일반적으로 다음과 같은 것을 사용하는 것으로 돌아갑니다.
long start = System.currentTimeMillis();
// ... do something ...
long end = System.currentTimeMillis();
또는 System.nanoTime ();
벤치마킹 측면에 대한 자세한 내용은 http://jetm.void.fm/ 결코 시도하지 않았습니다.
Spring은 JavaDoc에 따라 유틸리티 클래스 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());
산출:
StopWatch 'Performance Test Result': running time (millis) = 12829
-----------------------------------------
ms % Task name
-----------------------------------------
11907 036% Method 1
00922 064% Method 2
Aspects :
@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;
}
메서드 실행 시간을 훨씬 읽기 쉬운 형식으로 인쇄하는 메서드를 작성했습니다. 예를 들어 1 백만의 계승을 계산하려면 약 9 분이 걸립니다. 따라서 실행 시간은 다음과 같이 인쇄됩니다.
Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds
코드는 다음과 같습니다.
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");
}
}
벽시계 시간을 원한다면
long start_time = System.currentTimeMillis();
object.method();
long end_time = System.currentTimeMillis();
long execution_time = end_time - start_time;
"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 입니다.
결국 당신이 계획 한 것을 할 수 있다면 pls. 개미 작업 / 항아리와 함께 여기 커뮤니티와 다시 공유하십시오.
long startTime = System.currentTimeMillis();
// code goes here
long finishTime = System.currentTimeMillis();
long elapsedTime = finishTime - startTime; // elapsed time in milliseconds
몇 초 안에 결과를 얻기 위해 정답에서 코드를 수정했습니다.
long startTime = System.nanoTime();
methodCode ...
long endTime = System.nanoTime();
double duration = (double)(endTime - startTime) / (Math.pow(10, 9));
Log.v(TAG, "MethodName time (s) = " + duration);
다양한 측정 기기를 제공 하는 Metrics 라이브러리를 사용할 수 있습니다 . 종속성 추가 :
<dependencies>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${metrics.version}</version>
</dependency>
</dependencies>
그리고 환경에 맞게 구성하십시오.
메서드는 @Timed 로 주석을 달 수 있습니다 .
@Timed
public void exampleMethod(){
// some code
}
또는 Timer로 래핑 된 코드 조각 :
final Timer timer = metricsRegistry.timer("some_name");
final Timer.Context context = timer.time();
// timed code
context.stop();
집계 된 메트릭은 콘솔, 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
스프링 코어 프로젝트의 스톱워치 클래스를 사용할 수 있습니다.
암호:
StopWatch stopWatch = new StopWatch()
stopWatch.start(); //start stopwatch
// write your function or line of code.
stopWatch.stop(); //stop stopwatch
stopWatch.getTotalTimeMillis() ; ///get total time
스톱워치 문서 : 간단한 스톱워치 로 여러 작업의 타이밍을 허용하고 각 명명 된 작업의 총 실행 시간과 실행 시간을 노출합니다. System.currentTimeMillis () 사용을 감추어 애플리케이션 코드의 가독성을 높이고 계산 오류 가능성을 줄입니다. 이 개체는 스레드로부터 안전하도록 설계되지 않았으며 동기화를 사용하지 않습니다. 이 클래스는 일반적으로 프로덕션 애플리케이션의 일부가 아니라 개념 증명 및 개발 중에 성능을 확인하는 데 사용됩니다.
시간을 알고 싶다면 이런 식으로 시도 할 수 있습니다.
long startTime = System.currentTimeMillis();
//@ Method call
System.out.println("Total time [ms]: " + (System.currentTimeMillis() - startTime));
좋습니다. 이것은 함수의 간단한 간단한 타이밍에 사용되는 간단한 클래스입니다. 그 아래에 예가 있습니다.
public class Stopwatch {
static long startTime;
static long splitTime;
static long endTime;
public Stopwatch() {
start();
}
public void start() {
startTime = System.currentTimeMillis();
splitTime = System.currentTimeMillis();
endTime = System.currentTimeMillis();
}
public void split() {
split("");
}
public void split(String tag) {
endTime = System.currentTimeMillis();
System.out.println("Split time for [" + tag + "]: " + (endTime - splitTime) + " ms");
splitTime = endTime;
}
public void end() {
end("");
}
public void end(String tag) {
endTime = System.currentTimeMillis();
System.out.println("Final time for [" + tag + "]: " + (endTime - startTime) + " ms");
}
}
사용 예 :
public static Schedule getSchedule(Activity activity_context) {
String scheduleJson = null;
Schedule schedule = null;
/*->*/ Stopwatch stopwatch = new Stopwatch();
InputStream scheduleJsonInputStream = activity_context.getResources().openRawResource(R.raw.skating_times);
/*->*/ stopwatch.split("open raw resource");
scheduleJson = FileToString.convertStreamToString(scheduleJsonInputStream);
/*->*/ stopwatch.split("file to string");
schedule = new Gson().fromJson(scheduleJson, Schedule.class);
/*->*/ stopwatch.split("parse Json");
/*->*/ stopwatch.end("Method getSchedule");
return schedule;
}
콘솔 출력 샘플 :
Split time for [file to string]: 672 ms
Split time for [parse Json]: 893 ms
Final time for [get Schedule]: 1565 ms
Java 8에서는 이름 Instant
이 지정된 새 클래스 가 도입되었습니다. 문서에 따라 :
Instant는 타임 라인에서 나노초의 시작을 나타냅니다. 이 클래스는 시스템 시간을 나타내는 타임 스탬프를 생성하는 데 유용합니다. 순간의 범위는 long보다 큰 숫자를 저장해야합니다. 이를 달성하기 위해 클래스는 epoch-seconds를 나타내는 long과 nanosecond-of-second를 나타내는 int를 저장하며 항상 0에서 999,999,999 사이입니다. epoch-seconds는 1970-01-01T00 : 00 : 00Z의 표준 Java epoch에서 측정되며, epoch 이후의 순간은 양수 값을 가지며 이전 순간은 음의 값을 갖습니다. epoch-second 및 nanosecond 부분의 경우 더 큰 값은 항상 더 작은 값보다 타임 라인에서 늦습니다.
다음과 같이 사용할 수 있습니다.
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.001S
.
참고 URL : https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java
'code' 카테고리의 다른 글
IMG와 CSS 배경 이미지는 언제 사용합니까? (0) | 2020.09.29 |
---|---|
GitHub에서 직접 npm 패키지를 설치하는 방법은 무엇입니까? (0) | 2020.09.29 |
Android에서 사용자의 현재 위치를 얻는 가장 간단하고 강력한 방법은 무엇입니까? (0) | 2020.09.29 |
PostgreSQL 데이터베이스의 모든 테이블을 삭제하려면 어떻게해야합니까? (0) | 2020.09.28 |
PowerShell에서 코드를 어떻게 주석 처리합니까? (0) | 2020.09.28 |