问题
Is there a stopwatch in Java? On google I only find code of stopwatches which don\'t work - they always return 0 milliseconds.
This code that I found doesn\'t work but I don\'t see 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;
}
}
回答1:
You'll find one in
http://commons.apache.org/lang/
It's called
org.apache.commons.lang.time.StopWatch
But it roughly does the same as yours. If you're in for more precision, use
System.nanoTime()
See also this question here:
Time measuring overhead in Java
回答2:
Use Guava's 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 a few reasons:
- An alternate time source can be substituted, for testing or performance reasons.
- As documented by nanoTime, the value returned has no absolute meaning, and can only be interpreted as relative to another timestamp returned by nanoTime at a different time. Stopwatch is a more effective abstraction because it exposes only these relative values, not the 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"
回答3:
Now you can try something like:
Instant starts = Instant.now();
Thread.sleep(10);
Instant ends = Instant.now();
System.out.println(Duration.between(starts, ends));
Output is in ISO 8601.
回答4:
Spring provides an elegant org.springframework.util.StopWatch
Class (spring-core module).
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// Do something
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
回答5:
The code doesn't work because elapsed variable in getElapsedTimeSecs() is not a float/double.
回答6:
Use System.currentTimeMillis()
to get the start time and the 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 info at this tutorial
回答7:
There's no built in Stopwatch utility but as of JSR-310 (Java 8 Time) you can do this simply.
ZonedDateTime now = ZonedDateTime.now();
// Do stuff
long seconds = now.until(ZonedDateTime.now(), ChronoUnit.SECONDS);
I haven't benchmarked this properly but I would guess using Guava's Stopwatch is more effective.
回答8:
try this http://introcs.cs.princeton.edu/java/stdlib/Stopwatch.java.html
that's very easy
Stopwatch st = new Stopwatch();
// Do smth. here
double time = st.elapsedTime(); // the result in millis
This class is a part of stdlib.jar
回答9:
Simple out of the box Stopwatch class:
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;
}
}
Usage:
StopWatch sw = new StopWatch();
sw.start();
// doWork()
sw.stop();
System.out.println( sw.getElapsedTime().toMillis() + "ms");
回答10:
use : com.google.common.base.Stopwatch, its simple and easy.
<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
回答11:
try this
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();
}
}
回答12:
Try this:
/*
* 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));
}
}
Use:
StopWatch sw = new StopWatch();
...
sw.startTiming();
...
String interval = sw.stopTiming();
回答13:
Try this.
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;
}
}
Usage:
StopWatch watch = new StopWatch();
// do something
watch.stop();
Console:
StopWatch: 143 milliseconds.
StopWatch: 0.143 seconds.
回答14:
You can find a convenient one here:
https://github.com/varra4u/utils4j/blob/master/src/main/java/com/varra/util/StopWatch.java
Usage:
final StopWatch timer = new StopWatch();
System.out.println("Timer: " + timer);
System.out.println("ElapsedTime: " + timer.getElapsedTime());
回答15:
Try this.
Java Stopwatch Fully Working Solution
Here you will get a fully working solution.
Just a snippet from the above-linked solution:
You can create a class like below code and use this class' start and stop method before and after the code section, you want to measure the time taken.
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 you.
来源:https://stackoverflow.com/questions/8255738/is-there-a-stopwatch-in-java