Java中有秒表吗?在Google上,我只找到无法使用的秒表代码-它们总是返回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;
}
}
currentTimeMillis()
用于生产,因为它与系统日期/时间相关,并且不能保证其单调(例如,您可能会获得负的经过时间)。用于测量时间nanoTime()
–保证它是单调的,并且专门用于测量目的。见docs.oracle.com/javase/8/docs/api/java/lang/...