Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java stopwatch用法

作者:原来是梦   发布日期:2025-08-15   浏览:25

import java.time.Duration;
import java.time.Instant;

public class Stopwatch {

    private Instant startTime;
    private Instant endTime;
    private boolean running;

    public Stopwatch() {
        this.running = false;
    }

    // 开始计时
    public void start() {
        if (running) {
            throw new IllegalStateException("Stopwatch is already running");
        }
        startTime = Instant.now();
        running = true;
    }

    // 停止计时
    public void stop() {
        if (!running) {
            throw new IllegalStateException("Stopwatch is not running");
        }
        endTime = Instant.now();
        running = false;
    }

    // 获取经过的时间(以秒为单位)
    public double getElapsedTime() {
        if (running) {
            throw new IllegalStateException("Stopwatch is still running");
        }
        return Duration.between(startTime, endTime).getSeconds();
    }

    // 获取经过的时间(以毫秒为单位)
    public long getElapsedTimeMillis() {
        if (running) {
            throw new IllegalStateException("Stopwatch is still running");
        }
        return Duration.between(startTime, endTime).toMillis();
    }

    public static void main(String[] args) {
        Stopwatch stopwatch = new Stopwatch();

        // 开始计时
        stopwatch.start();

        // 模拟一些耗时操作
        try {
            Thread.sleep(2000); // 睡眠2秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 停止计时
        stopwatch.stop();

        // 输出经过的时间
        System.out.println("Elapsed time in seconds: " + stopwatch.getElapsedTime());
        System.out.println("Elapsed time in milliseconds: " + stopwatch.getElapsedTimeMillis());
    }
}

解释说明:

  1. 类定义Stopwatch 类用于实现一个简单的计时器功能。
  2. 属性
    • startTimeendTime:分别记录开始时间和结束时间,使用 Instant 类表示。
    • running:布尔值,用于标记计时器是否正在运行。
  3. 方法
    • start():开始计时,记录当前时间为 startTime
    • stop():停止计时,记录当前时间为 endTime
    • getElapsedTime():返回经过的时间(以秒为单位)。
    • getElapsedTimeMillis():返回经过的时间(以毫秒为单位)。
  4. 主程序:在 main 方法中创建了一个 Stopwatch 对象,模拟了一个耗时操作(线程睡眠2秒),然后输出经过的时间。

上一篇:java生成唯一id

下一篇:sleep和wait的区别java

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站