有没有Java的秒表?
有没有Java的秒表? 因为在谷歌我只能find秒表的代码,他们不工作,他们给我总是0毫秒。
我发现这个代码不起作用,但我不明白为什么,因为代码对我来说看起来很好。
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; } }
你会find一个
http://commons.apache.org/lang/
这叫
org.apache.commons.lang.time.StopWatch
但它大体上和你的一样。 如果你在更精确的使用
System.nanoTime()
这里也看到这个问题:
用Java测量开销
使用番石榴的秒表类 。
一个以纳秒为单位度量经过时间的对象。 使用这个类来测量已用时间非常有用,而不是直接调用System.nanoTime(),原因如下:
- 出于testing或性能原因,可以替代备用时间源。
- 如nanoTime所logging的,返回的值没有绝对的含义,只能解释为相对于nanoTime在不同时间返回的另一个时间戳。 秒表是一个更有效的抽象,因为它只暴露这些相对值,而不是绝对值。
Stopwatch stopwatch = Stopwatch.createStarted(); doSomething(); stopwatch.stop(); // optional long millis = stopwatch.elapsedMillis(); log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
Spring提供了一个优雅的StopWatch类。
StopWatch stopWatch = new StopWatch(); stopWatch.start(); // Do something stopWatch.stop(); System.out.println(stopWatch.getTotalTimeMillis());
现在你可以尝试像这样:
Instant starts = Instant.now(); Thread.sleep(10); Instant ends = Instant.now(); System.out.println(Duration.between(starts, ends));
输出在ISO 8601中。
代码不起作用,因为getElapsedTimeSecs()中的已variablesvariables不是float / double。
使用System.currentTimeMillis()
获取开始时间和结束时间并计算差异。
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); } }
更多信息在这个教程
有没有内置的秒表工具,但从JSR-310(Java 8时间),你可以做到这一点。
ZonedDateTime now = ZonedDateTime.now(); // Do stuff long seconds = now.until(ZonedDateTime.now(), ChronoUnit.SECONDS);
我没有正确的基准,但我猜想使用番石榴的秒表更有效。
尝试这个
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(); } }
试试这个http://introcs.cs.princeton.edu/java/stdlib/Stopwatch.java.html
这很容易
Stopwatch st = new Stopwatch(); // Do smth. here double time = st.elapsedTime(); // the result in millis
这个类是stdlib.jar的一部分
简单的开箱秒表课程:
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; } }
用法:
StopWatch sw = new StopWatch(); sw.start(); // doWork() sw.stop(); System.out.println( sw.getElapsedTime().toMillis() + "ms");
尝试这个:
/* * 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)); } }
使用:
StopWatch sw = new StopWatch(); ... sw.startTiming(); ... String interval = sw.stopTiming();
user1007522,我不知道为什么你的代码不起作用(看起来像已经评论过),但我刚刚从com.google.common.base.Stopwatch获得0毫秒相同的问题。
我在做
Stopwatch stopwatch = new Stopwatch(); doSomething(); logger.info("test took:" + stopwatch);
现在我在做
Stopwatch stopwatch = new Stopwatch().start(); doSomething(); stopwatch.stop(); logger.info("test took:" + stopwatch);
它工作,我得到“testing了:26.81秒”
你可以在这里find一个方便的:
https://github.com/varra4u/utils4j/blob/master/src/main/java/com/varra/util/StopWatch.java
用法:
final StopWatch timer = new StopWatch(); System.out.println("Timer: " + timer); System.out.println("ElapsedTime: " + timer.getElapsedTime());
尝试这个。
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; } }
用法:
StopWatch watch = new StopWatch(); // do something watch.stop();
安慰:
StopWatch: 143 milliseconds. StopWatch: 0.143 seconds.
使用:com.google.common.base.Stopwatch,其简单易用。
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency>
例:
Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); "Do something" logger.debug("this task took " + stopwatch.stop().elapsedTime(TimeUnit.MILLISECONDS) + " mills");
这个任务花了112个工厂