java stopwatch
时间: 2023-09-14 09:12:11 浏览: 111
JAVA_stopwatch_clock.rar_java stopwatch
以下是一个简单的 Java Stopwatch 类的示例代码:
```
public class Stopwatch {
private long startTime;
private long stopTime;
private boolean isRunning;
public void start() {
this.startTime = System.currentTimeMillis();
this.isRunning = true;
}
public void stop() {
this.stopTime = System.currentTimeMillis();
this.isRunning = false;
}
public long getElapsedTime() {
long elapsed;
if (isRunning) {
elapsed = (System.currentTimeMillis() - startTime);
} else {
elapsed = (stopTime - startTime);
}
return elapsed;
}
public void reset() {
this.startTime = 0;
this.stopTime = 0;
this.isRunning = false;
}
}
```
使用示例:
```
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
// some code to be timed...
stopwatch.stop();
long elapsedTime = stopwatch.getElapsedTime();
System.out.println("Elapsed time in milliseconds: " + elapsedTime);
```
该类具有以下方法:
- `start()`:启动计时器。
- `stop()`:停止计时器。
- `getElapsedTime()`:获取经过的时间(以毫秒为单位)。
- `reset()`:重置计时器。
你可以根据需要对该类进行修改和扩展,例如添加格式化输出等功能。
阅读全文