程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> 使用StopWatch類輸出時間戳

使用StopWatch類輸出時間戳

編輯:JAVA編程入門知識

  package com.generationJava.test;
  
  /**
  
  * Useful when doing timings in a debug or test situation.
  
  */
  
  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;
  
  /**
  
  * Start the stopwatch.
  
  */
  
  public void start() {
  
  this.startTime = System.currentTimeMillis();
  
  }
  
  /**
  
  * Stop the stopwatch.
  
  */
  
  public void stop() {
  
  this.stopTime = System.currentTimeMillis();
  
  }
  
  /**
  
  * Reset the stopwatch.
  
  */
  
  public void reset() {
  
  this.startTime = -1;
  
  this.stopTime = -1;
  
  }
  
  /**
  
  * Split the time.
  
  */
  
  public void split() {
  
  this.stopTime = System.currentTimeMillis();
  
  }
  
  /**
  
  * Remove a split.
  
  */
  
  public void unsplit() {
  
  this.stopTime = -1;
  
  }
  
  /**
  
  * Get the time on the stopwatch. This is either the
  
  * time between start and latest split, between start and stop,
  
  * or the time between the start and the moment this method is called.
  
  */
  
  public long getTime() {
  
  if(stopTime != -1) {
  
  return (System.currentTimeMillis() - this.startTime);
  
  } else {
  
  return this.stopTime - this.startTime;
  
  }
  
  }
  
  public String toString() {
  
  return getTimeString();
  
  }
  
  /**
  
  * Get the time gap as a String.
  
  * In hours, minutes, seconds and milliseconds.
  
  */
  
  public String getTimeString() {
  
  int hours, minutes, seconds, milliseconds;
  
  long time = getTime();
  
  hours = (int) (time / AN_HOUR);
  
  time = time - (hours * AN_HOUR);
  
  minutes = (int) (time / A_MINUTE);
  
  time = time - (minutes * A_MINUTE);
  
  seconds = (int) (time / 1000);
  
  time = time - (seconds * 1000);
  
  millis = (int) time;
  
  return hours + "h:" + minutes + "m:" + seconds + "s:" + millis + "ms";
  
  }
  
  }
 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved