How do I time a method's execution in Java?

前端 未结 30 2735
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 11:44

    Ok, this is a simple class to be used for simple simple timing of your functions. There is an example below it.

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

    Sample of use:

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

    Sample of console output:

    Split time for [file to string]: 672 ms
    Split time for [parse Json]: 893 ms
    Final time for [get Schedule]: 1565 ms
    

提交回复
热议问题