long startTime = System.nanoTime();methodToTime();long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
String watchTag = "target.SomeMethod";StopWatch stopWatch = new LoggingStopWatch(watchTag);Result result = null; // Result is a type of a return value of a methodtry {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()));}
}
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;}
}
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 msSplit time for [parse Json]: 893 msFinal time for [get Schedule]: 1565 ms
StopWatch stopWatch = new StopWatch("Performance Test Result");
stopWatch.start("Method 1");doSomething1();//method to teststopWatch.stop();
stopWatch.start("Method 2");doSomething2();//method to teststopWatch.stop();
System.out.println(stopWatch.prettyPrint());
输出:
StopWatch 'Performance Test Result': running time (millis) = 12829-----------------------------------------ms % Task name-----------------------------------------11907 036% Method 100922 064% Method 2
StopWatch sw = new org.springframework.util.StopWatch();sw.start("Method-1"); // Start a named taskThread.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 :999Table describing all tasks performed :StopWatch '': running time (millis) = 999-----------------------------------------ms % Task name-----------------------------------------00500 050% Method-100299 030% Method-200200 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]
public class Timer{private static long start_time;
public static double tic(){return start_time = System.nanoTime();}
public static double toc(){return (System.nanoTime()-start_time)/1000000000.0;}
}
StopWatch stopWatch = new StopWatch()stopWatch.start(); //start stopwatch// write your function or line of code.stopWatch.stop(); //stop stopwatchstopWatch.getTotalTimeMillis() ; ///get total time
public static void main(String[] args) {
Integer square = new TimeTracedExecutor<>(Main::calculateSquare).executeWithInput("calculate square of num",5,logger);
}public static int calculateSquare(int num){return num*num;}
会产生这样的结果:
INFO: It took 3 milliseconds to calculate square of num
自定义可重用类:执行人
import java.text.NumberFormat;import java.time.Duration;import java.time.Instant;import java.util.function.Function;import java.util.logging.Logger;
public class TimeTracedExecutor<T,R> {Function<T,R> methodToExecute;
public TimeTracedExecutor(Function<T, R> methodToExecute) {this.methodToExecute = methodToExecute;}
public R executeWithInput(String taskDescription, T t, Logger logger){Instant start = Instant.now();R r= methodToExecute.apply(t);Instant finish = Instant.now();String format = "It took %s milliseconds to "+taskDescription;String elapsedTime = NumberFormat.getNumberInstance().format(Duration.between(start, finish).toMillis());logger.info(String.format(format, elapsedTime));return r;}}
//measuring elapsed time using Spring StopWatchStopWatch 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());
Duration result = Timing.time(() -> {// do some work.});
TimedResult<String> result = Timing.time(() -> {// do some work.return "answer";});
Duration timeTaken = result.duration();String answer = result.result();