Java中有秒表吗? [英] Is there a stopwatch in Java?
本文介绍了Java中有秒表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java中有秒表吗?在谷歌我只找到不起作用的秒表代码 - 它们总是返回0毫秒。
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;
}
}
推荐答案
你我会找到一个
http:// commons。 apache.org/lang/
这叫做
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:
这篇关于Java中有秒表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文