SoFunction
Updated on 2025-04-07

Detailed explanation of the usage of StopWatch tool class in Java

stopWatch is a tool class under the package, which can use it to intuitively output code execution time and execution time percentage.

Before using this tool class, if we need to count the time-consuming of a certain piece of code, we will write this:

public static void main(String[] args) throws InterruptedException {
    test0();
}
 
public static void test0() throws InterruptedException {
    long start = ();
    // do something
    (100);
    long end = ();
    long start2 = ();
    // do somethind
    long end2 = ();
 
    ("So-1 execution takes time:" + (end -start));
    ("So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So-So- + (end2 -start2));
 
    
}

An example of using stopWatch instead

public class StopWatchDemo {
 
    public static void main(String[] args) throws InterruptedException {
         test1();
    }
 
     public static void test1() throws InterruptedException {
 
       StopWatch sw = new StopWatch("test");
       ("task1");
       // do something
       (100);
       ();
       ("task2");
       // do someting
       (200);
       ();
       ("()-------");
       (());
 
 
    }
 
 
}

The operation results are as follows:

()------
StopWatch 'test': running time (millis) = 310
-----------------------------------------
ms     %     Task name
-----------------------------------------
00110  035%  task1
00200  065%  task2

The start and end times are recorded separately through the start and stop methods. When recording the end time, a taskList attribute of a linked list type will be maintained, so that this class can record multiple tasks. The last output page only makes a unified inductive output of the previous record information.

import ;
import ;
import ;
 
public class StopWatch {
    private final String id;
    private boolean keepTaskList = true;
    private final List<TaskInfo> taskList = new LinkedList();
    private long startTimeMillis;
    private boolean running;
    private String currentTaskName;
    private  lastTaskInfo;
    private int taskCount;
    private long totalTimeMillis;
 
    public StopWatch() {
         = "";
    }
 
    public StopWatch(String id) {
         = id;
    }
 
    public void setKeepTaskList(boolean keepTaskList) {
         = keepTaskList;
    }
 
    public void start() throws IllegalStateException {
        ("");
    }
 
    public void start(String taskName) throws IllegalStateException {
        if () {
            throw new IllegalStateException("Can't start StopWatch: it's already running");
        } else {
             = ();
             = true;
             = taskName;
        }
    }
 
    public void stop() throws IllegalStateException {
        if (!) {
            throw new IllegalStateException("Can't stop StopWatch: it's not running");
        } else {
            long lastTime = () - ;
             += lastTime;
             = new (, lastTime);
            if () {
                ();
            }
 
            ++;
             = false;
             = null;
        }
    }
 
    public boolean isRunning() {
        return ;
    }
 
    public long getLastTaskTimeMillis() throws IllegalStateException {
        if ( == null) {
            throw new IllegalStateException("No tasks run: can't get last task interval");
        } else {
            return ();
        }
    }
 
    public String getLastTaskName() throws IllegalStateException {
        if ( == null) {
            throw new IllegalStateException("No tasks run: can't get last task name");
        } else {
            return ();
        }
    }
 
    public  getLastTaskInfo() throws IllegalStateException {
        if ( == null) {
            throw new IllegalStateException("No tasks run: can't get last task info");
        } else {
            return ;
        }
    }
 
    public long getTotalTimeMillis() {
        return ;
    }
 
    public double getTotalTimeSeconds() {
        return (double)  / 1000.0D;
    }
 
    public int getTaskCount() {
        return ;
    }
 
    public [] getTaskInfo() {
        if (!) {
            throw new UnsupportedOperationException("Task info is not being kept!");
        } else {
            return ([]) (new [()]);
        }
    }
 
    public String shortSummary() {
        return "StopWatch '" +  + "': running time (millis) = " + ();
    }
 
    public String prettyPrint() {
        StringBuilder sb = new StringBuilder(());
        ('\n');
        if (!) {
            ("No task info kept");
        } else {
            ("-----------------------------------------\n");
            ("ms     %     Task name\n");
            ("-----------------------------------------\n");
            NumberFormat nf = ();
            (5);
            (false);
            NumberFormat pf = ();
            (3);
            (false);
            [] var7;
            int var6 = (var7 = ()).length;
 
            for (int var5 = 0; var5 < var6; ++var5) {
                 task = var7[var5];
                ((())).append("  ");
                ((() / ())).append("  ");
                (()).append("\n");
            }
        }
 
        return ();
    }
 
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(());
        if () {
            [] var5;
            int var4 = (var5 = ()).length;
 
            for (int var3 = 0; var3 < var4; ++var3) {
                 task = var5[var3];
                ("; [").append(()).append("] took ").append(());
                long percent = (100.0D * () / ());
                (" = ").append(percent).append("%");
            }
        } else {
            ("; no task info kept");
        }
 
        return ();
    }
 
    public static final class TaskInfo {
        private final String taskName;
        private final long timeMillis;
 
        TaskInfo(String taskName, long timeMillis) {
             = taskName;
             = timeMillis;
        }
 
        public String getTaskName() {
            return ;
        }
 
        public long getTimeMillis() {
            return ;
        }
 
        public double getTimeSeconds() {
            return (double)  / 1000.0D;
        }
    }
 
}

This is the end of this article about the detailed explanation of the usage of StopWatch tool class in Java. For more related Java StopWatch content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!