爱心技术专栏专题

使用StopWatch类来计时

摘录:java 来源:java 加入时间:2007年03月19日
摘要:
使用StopWatch类来计时

  调试器是一个繁重的东西,使用调试器并不总是最有效的方法;有时,你可能想对代码进行一些小的调试和跟踪。一个简单的StopWatch类就是提供了一种好的计时解决方案。

  1. package com.generationjava.test; <…

    转载:转载请保留本信息,本文来自
    http://www.51dibs.com
    /html/2006/article/info11/a_e9fb4c8b207ba165.htm

使用StopWatch类来计时

站点:爱心种子小博士 关键字:使用StopWatch类来计时

   
使用StopWatch类来计时
  调试器是一个繁重的东西,使用调试器并不总是最有效的方法;有时,你可能想对代码进行一些小的调试和跟踪。一个简单的StopWatch类就是提供了一种好的计时解决方案。

  1. package com.generationjava.test;
  2. /**
  3.  * 在调试或者测试情形下需要计时非常有用
  4.  */
  5. public class StopWatch {
  6.   static public int AN_HOUR = 60 * 60 * 1000;
  7.   static public int A_MINUTE = 60 * 1000;
  8.   private long startTime = -1;
  9.   private long stopTime = -1;
  10.   /**
  11.    * 启动秒表
  12.    */
  13.   public void start() {
  14.     this.startTime =System.currentTimeMillis();
  15.   }
  16.   /**
  17.    * 停止秒表
  18.    */
  19.   public void stop() {
  20.     this.stopTime =System.currentTimeMillis();
  21.   }
  22.   /**
  23.    * 重置秒表
  24.    */
  25.   public void reset() {
  26.     this.startTime = -1;
  27.     this.stopTime = -1;
  28.   }
  29.   /**
  30.    * 分割时间
  31.    */
  32.   public void split() {
  33.     this.stopTime =System.currentTimeMillis();
  34.   }
  35.   /**
  36.    * 移除分割
  37.    */
  38.   public void unsplit() {
  39.     this.stopTime = -1;
  40.   }
  41.   /**
  42.    * 获得秒表的时间,这个时间或者是启动时和最后一个分割时刻的时间差,
  43.    * 或者是启动时和停止时的时间差,或者是启动时和这个方法被调用时的差
  44.    */
  45.   public long getTime() {
  46.     if(stopTime != -1) {
  47.       return(System.currentTimeMillis() - this.startTime);
  48.     } else {
  49.       return this.stopTime - this.startTime;
  50.     }
  51.   }
  52.   public String toString() {
  53.     return getTimeString();
  54.   }
  55.   /**
  56.    * 取得String类型的时间差
  57.    * 形式为小时,分钟,秒和毫秒
  58.    */
  59.   public String getTimeString() {
  60.     int hours, minutes, seconds,milliseconds;
  61.     long time = getTime();
  62.     hours = (int) (time / AN_HOUR);
  63.     time = time - (hours *AN_HOUR);
  64.     minutes = (int) (time /A_MINUTE);
  65.     time = time - (minutes *A_MINUTE);
  66.     seconds = (int) (time / 1000);
  67.     time = time - (seconds * 1000);
  68.     milliseconds = (int) time;
  69.     return hours + "h:" +minutes + "m:"
  70.      + seconds + "s:" + milliseconds +
  71.   }


  与大块的代码相比,它是非常简单的。但是它可重用而毫不复杂。因此StopWatch类的使用也是非常简单的:

  1. StopWatch obj = new StopWatch();
  2. obj.start();
  3. try{
  4.   Thread.currentThread().sleep(1500);
  5. }catch(InterruptedException ie) {
  6.   // ignore
  7. }
  8. obj.stop();
  9. System.out.println(obj); 

  
  我们执行了1500豪秒sleep,完全在预料之中的,StopWatch的报告为:

  0h:0m:1s:502ms 

  StopWatch不是深奥复杂的科学,但是它确实满足了常见的测量代码行间执行时间的需求。

(本文是为ZDNet翻译的系列文章之一,原文已经发表在ZDNet网站)