Is there a stopwatch in Java?

Is there a stopwatch in Java? On Google, I only find stopwatch codes that don't work - they always return 0 milliseconds.

This code I found does not work, but I do not understand why.

public class StopWatch { private long startTime = 0; private long stopTime = 0; private boolean running = false; public void start() { this.startTime = System.currentTimeMillis(); this.running = true; } public void stop() { this.stopTime = System.currentTimeMillis(); this.running = false; } //elaspsed time in milliseconds public long getElapsedTime() { long elapsed; if (running) { elapsed = (System.currentTimeMillis() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed; } //elaspsed time in seconds public long getElapsedTimeSecs() { long elapsed; if (running) { elapsed = ((System.currentTimeMillis() - startTime) / 1000); } else { elapsed = ((stopTime - startTime) / 1000); } return elapsed; } } 
+94
java stopwatch
Nov 24 2018-11-11T00:
source share
16 answers

You will find him in

http://commons.apache.org/lang/

It is called

 org.apache.commons.lang.time.StopWatch 

But he roughly does the same as yours. If you need higher accuracy, use

 System.nanoTime() 

See also this question:

Java time overhead

+83
Nov 24 '11 at 10:44
source share

Use the Guava Stopwatch class .

An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using this class instead of direct calls to System.nanoTime() for several reasons:

  • An alternative time source can be replaced for testing or to improve performance.
  • As nanoTime is documented, the return value does not have an absolute value and can only be interpreted as the relative value of another timestamp returned by nanoTime at another time. Stopwatch is a more effective abstraction because it shows only these relative values, not absolute ones.
 Stopwatch stopwatch = Stopwatch.createStarted(); doSomething(); stopwatch.stop(); // optional long millis = stopWatch.elapsed(TimeUnit.MILLISECONDS); log.info("that took: " + stopwatch); // formatted string like "12.3 ms" 
+80
Nov 24 '11 at 10:44
source share

Now you can try something like:

 Instant starts = Instant.now(); Thread.sleep(10); Instant ends = Instant.now(); System.out.println(Duration.between(starts, ends)); 

The output is in ISO 8601.

+46
Nov 03 '15 at 9:43
source share

Spring provides an elegant class org.springframework.util.StopWatch (spring core module).

 StopWatch stopWatch = new StopWatch(); stopWatch.start(); // Do something stopWatch.stop(); System.out.println(stopWatch.getTotalTimeMillis()); 
+33
Dec 06
source share

The code does not work because the passed variable in getElapsedTimeSecs () is not float / double.

+7
Aug 23 2018-12-23T00:
source share

Use System.currentTimeMillis() to get the start time and end time and calculate the difference.

 class TimeTest1 { public static void main(String[] args) { long startTime = System.currentTimeMillis(); long total = 0; for (int i = 0; i < 10000000; i++) { total += i; } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.println(elapsedTime); } } 

More information in this tutorial.

+5
May 24 '13 at
source share

There is no built-in stopwatch utility, but with JSR-310 (Java 8 Time) you can do it simply.

 ZonedDateTime now = ZonedDateTime.now(); // Do stuff long seconds = now.until(ZonedDateTime.now(), ChronoUnit.SECONDS); 

I did not evaluate this correctly, but I would suggest that using Guava Stopwatch is more efficient.

+5
Jul 09 '15 at 9:50
source share

try http://introcs.cs.princeton.edu/java/stdlib/Stopwatch.java.html

which is very easy

 Stopwatch st = new Stopwatch(); // Do smth. here double time = st.elapsedTime(); // the result in millis 

This class is part of stdlib.jar

+2
Sep 21 '13 at 17:34
source share

Simple of the class Stopwatch:

 import java.time.Duration; import java.time.Instant; public class StopWatch { Instant startTime, endTime; Duration duration; boolean isRunning = false; public void start() { if (isRunning) { throw new RuntimeException("Stopwatch is already running."); } this.isRunning = true; startTime = Instant.now(); } public Duration stop() { this.endTime = Instant.now(); if (!isRunning) { throw new RuntimeException("Stopwatch has not been started yet"); } isRunning = false; Duration result = Duration.between(startTime, endTime); if (this.duration == null) { this.duration = result; } else { this.duration = duration.plus(result); } return this.getElapsedTime(); } public Duration getElapsedTime() { return this.duration; } public void reset() { if (this.isRunning) { this.stop(); } this.duration = null; } } 

Using:

 StopWatch sw = new StopWatch(); sw.start(); // doWork() sw.stop(); System.out.println( sw.getElapsedTime().toMillis() + "ms"); 
+2
Apr 21 '16 at 3:15
source share

use: com.google.common.base.Stopwatch, its simple and simple.

 <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency> 

example:

 Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); "Do something" logger.debug("this task took " + stopwatch.stop().elapsedTime(TimeUnit.MILLISECONDS) + " mills"); 

this task took 112 mills

+2
Sep 26 '17 at 9:13
source share

try it

 import java.awt.event.*; import java.awt.*; import javax.swing.*; public class millis extends JFrame implements ActionListener, Runnable { private long startTime; private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS"); private final JButton startStopButton= new JButton("Start/stop"); private Thread updater; private boolean isRunning= false; private final Runnable displayUpdater= new Runnable() { public void run() { displayElapsedTime(System.currentTimeMillis() - millis.this.startTime); } }; public void actionPerformed(ActionEvent ae) { if(isRunning) { long elapsed= System.currentTimeMillis() - startTime; isRunning= false; try { updater.join(); // Wait for updater to finish } catch(InterruptedException ie) {} displayElapsedTime(elapsed); // Display the end-result } else { startTime= System.currentTimeMillis(); isRunning= true; updater= new Thread(this); updater.start(); } } private void displayElapsedTime(long elapsedTime) { startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime))); } public void run() { try { while(isRunning) { SwingUtilities.invokeAndWait(displayUpdater); Thread.sleep(50); } } catch(java.lang.reflect.InvocationTargetException ite) { ite.printStackTrace(System.err); // Should never happen! } catch(InterruptedException ie) {} // Ignore and return! } public millis() { startStopButton.addActionListener(this); getContentPane().add(startStopButton); setSize(100,50); setVisible(true); } public static void main(String[] arg) { new Stopwatch().addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); millis s=new millis(); s.run(); } } 
+1
Nov 07 '12 at 16:19
source share

Try the following:

 /* * calculates elapsed time in the form hrs:mins:secs */ public class StopWatch { private Date startTime; public void startTiming() { startTime = new Date(); } public String stopTiming() { Date stopTime = new Date(); long timediff = (stopTime.getTime() - startTime.getTime())/1000L; return(DateUtils.formatElapsedTime(timediff)); } } 

Using:

 StopWatch sw = new StopWatch(); ... sw.startTiming(); ... String interval = sw.stopTiming(); 
+1
Jan 24 '14 at 0:35
source share

Try it.

 public class StopWatch { private long startTime = 0; private long stopTime = 0; public StopWatch() { startTime = System.currentTimeMillis(); } public void start() { startTime = System.currentTimeMillis(); } public void stop() { stopTime = System.currentTimeMillis(); System.out.println("StopWatch: " + getElapsedTime() + " milliseconds."); System.out.println("StopWatch: " + getElapsedTimeSecs() + " seconds."); } /** * @param process_name */ public void stop(String process_name) { stopTime = System.currentTimeMillis(); System.out.println(process_name + " StopWatch: " + getElapsedTime() + " milliseconds."); System.out.println(process_name + " StopWatch: " + getElapsedTimeSecs() + " seconds."); } //elaspsed time in milliseconds public long getElapsedTime() { return stopTime - startTime; } //elaspsed time in seconds public double getElapsedTimeSecs() { double elapsed; elapsed = ((double)(stopTime - startTime)) / 1000; return elapsed; } } 

Using:

 StopWatch watch = new StopWatch(); // do something watch.stop(); 

Console:

 StopWatch: 143 milliseconds. StopWatch: 0.143 seconds. 
+1
Jul 06 '17 at 5:38 on
source share

user1007522, I don’t know why your code is not working (it seems asfer already commented on this), but I had the same problem getting 0 miliseconds from com.google.common.base.Stopwatch.

I was doing

 Stopwatch stopwatch = new Stopwatch(); doSomething(); logger.info("test took:" + stopwatch); 

Now i do

 Stopwatch stopwatch = new Stopwatch().start(); doSomething(); stopwatch.stop(); logger.info("test took:" + stopwatch); 

and it works, I get "test took: 26.81 s"

0
Oct 16 '13 at 15:32
source share

Here you can find convenient:

https://github.com/varra4u/utils4j/blob/master/src/main/java/com/varra/util/StopWatch.java

Using:

 final StopWatch timer = new StopWatch(); System.out.println("Timer: " + timer); System.out.println("ElapsedTime: " + timer.getElapsedTime()); 
0
Mar 27 '16 at 9:12
source share

Try this.

Java Stopwatch A Fully Working Solution

Here you get a fully working solution.

Just a snippet from the above solution:

You can create a class like the one below and use the start and stop method of this class before and after the code section where you want to measure time.

 public class Stopwatch{ private long startTime; private long stopTime; /** starting the stop watch. */ public void start(){ startTime = System.nanoTime(); } /** stopping the stop watch. */ public void stop() { stopTime = System.nanoTime(); } /** elapsed time in nanoseconds. */ public long time(){ return (stopTime - startTime); } public String toString(){ return "elapsed time: " + time() + " nanoseconds."; } 

}

Thank.

0
Jul 18 '19 at 6:31
source share



All Articles