Java 里有秒表吗?

Java 里有秒表吗?
在谷歌上我只找到了不能用的秒表代码——它们总是返回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;
}
}
275094 次浏览

你会在里面找到的

Http://commons.apache.org/lang/

叫做

org.apache.commons.lang.time.StopWatch

但是它的功能和你的差不多,如果你想要更精确的,那就用

System.nanoTime()

这里还有一个问题:

Java 中的时间测量开销

使用 番石榴 Stopwatch

以纳秒为单位测量运行时间的对象 使用此类而不是直接调用 System.nanoTime()基于以下几个原因:

  • 由于测试或性能方面的原因,可以替换时间源。
  • 如 nanTime 所记录的,返回的值没有绝对意义,只能被解释为相对于另一个时间戳 在不同的时间由纳米时间返回 有效的抽象,因为它只暴露这些相对值, 不是绝对的。
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"

代码不工作,因为在 getElapsedTimeSecs()中运行的变量不是 floatdouble

试试这个

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

Spring 提供了一个优雅的 org.springframework.util.StopWatch类(spring-core模块)。

StopWatch stopWatch = new StopWatch();


stopWatch.start();
// Do something
stopWatch.stop();


System.out.println(stopWatch.getTotalTimeMillis());

使用 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);
}
}

本教程提供更多信息

试试这个 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 的一部分

试试这个:

/*
* 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();

没有内置的 Stopwatch 实用程序,但是从 JSR-310(Java8 Time)开始,您可以简单地完成这项工作。

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

我还没有正确的基准测试这个,但我猜使用番石榴的秒表更有效。

现在你可以试试这样:

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

输出为 ISO8601。

你可以在这里找到一个方便的方法:

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());

开箱即用的秒表类:

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

试试这个。

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.

Use.com.google.common.base. 秒表,简单易用。

<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个磨坊

试试这个。

全功能秒表解决方案

在这里,您将得到一个完全可行的解决方案。

只是上面链接的解决方案中的一个片段:

您可以创建一个类(如下面的代码) ,并在代码部分之前和之后使用该类的 start 和 stop 方法,您希望测量所花费的时间。

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

}

谢谢你。

Performetrics 提供了一个方便的 Stopwatch 类,正是您需要的方式。它可以测量墙时钟时间和更多: 它还测量 CPU 时间(用户时间和系统时间) ,如果你需要。 它很小,免费,你可以从 Maven Central 下载。 更多的信息和例子可以在这里找到: < a href = “ https://obvj.net/Performmetrics”rel = “ nofollow norefrer”> https://obvj.net/performetrics

Stopwatch sw = new Stopwatch();
sw.start();


// Your code


sw.stop();
sw.printStatistics(System.out);


// Sample output:
// +-----------------+----------------------+--------------+
// | Counter         |         Elapsed time | Time unit    |
// +-----------------+----------------------+--------------+
// | Wall clock time |             85605718 | nanoseconds  |
// | CPU time        |             78000500 | nanoseconds  |
// | User time       |             62400400 | nanoseconds  |
// | System time     |             15600100 | nanoseconds  |
// +-----------------+----------------------+--------------+

您可以将指标转换为任何时间单位(纳秒、毫秒、秒等)

PS: 我是这个工具的作者。

试试这个..。

import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;


public class StopwatchTest {
     

public static void main(String[] args) throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
Thread.sleep(1000 * 60);
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("Time in milliseconds "+millis);
System.out.println("that took: " + stopwatch);
}
}

我已经创建了一个 秒表,其中包含你可能需要的一切。

我甚至 记录在案它!

我也编辑了更快的使用。

这里有一个例子:

//...
//For demo only!
public static void main(String[]a){
final Stopwatch stopwatch=new Stopwatch();
stopwatch.start();
try{
java.lang.Thread.sleep(1000);
}catch(Exception e){}
stopwatch.split();
System.out.println("Time elapsed in nanoseconds: "+stopwatch.getTimeElapsed());
System.out.println("Time elapsed in milliseconds: "+stopwatch.getTimeElapsed(Stopwatch.millis));
System.out.println("Time elapsed in seconds: "+stopwatch.getTimeElapsed(Stopwatch.seconds));
try{
java.lang.Thread.sleep(1000);
}catch(Exception e){}
stopwatch.split();
final long[][] laps=stopwatch.getLaps();
for(long[] lap:laps){
System.out.println(java.util.Arrays.toString(lap));
}
}
//...

这不是为了促销,做了这个是为了帮助人们不要把时间浪费在自己编码类上!