首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

StopWatch 工具類:精準計時與時間格式化輸出

     編輯:Java 程式設計入門

功能簡介

StopWatch 類提供碼錶功能,支援啟動、停止、重置、分段計時,並能以「時:分:秒:毫秒」格式輸出經過時間,適合除錯與效能測試場景。

核心 API

  • start():記錄開始時間(System.currentTimeMillis())
  • stop():記錄結束時間
  • reset():重置計時器
  • split() / unsplit():分段計時控制
  • getTime():取得經過毫秒數
  • getTimeString():取得格式化字串(如 1h:30m:45s:123ms)
  • toString():直接回傳格式化時間字串

原始碼完整實現

package com.generationJava.test;

public class StopWatch {
    static public int AN_HOUR = 60 * 60 * 1000;
    static public int A_MINUTE = 60 * 1000;

    private long startTime = -1;
    private long stopTime = -1;

    public void start() {
        this.startTime = System.currentTimeMillis();
    }

    public void stop() {
        this.stopTime = System.currentTimeMillis();
    }

    public void reset() {
        this.startTime = -1;
        this.stopTime = -1;
    }

    public void split() {
        this.stopTime = System.currentTimeMillis();
    }

    public void unsplit() {
        this.stopTime = -1;
    }

    public long getTime() {
        if (stopTime != -1) {
            return (System.currentTimeMillis() - this.startTime);
        } else {
            return this.stopTime - this.startTime;
        }
    }

    public String toString() {
        return getTimeString();
    }

    public String getTimeString() {
        int hours, minutes, seconds, milliseconds;
        long time = getTime();
        hours = (int) (time / AN_HOUR);
        time -= hours * AN_HOUR;
        minutes = (int) (time / A_MINUTE);
        time -= minutes * A_MINUTE;
        seconds = (int) (time / 1000);
        time -= seconds * 1000;
        milliseconds = (int) time;
        return hours + "h:" + minutes + "m:" + seconds + "s:" + milliseconds + "ms";
    }
}

使用範例

StopWatch sw = new StopWatch();
sw.start();
// 執行待測程式碼
sw.stop();
System.out.println("耗時:" + sw.getTimeString());

輸出範例:耗時:0h:0m:3s:245ms

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved