ITPub博客

首页 > Linux操作系统 > Linux操作系统 > [转载]使用StopWatch类来计时

[转载]使用StopWatch类来计时

原创 Linux操作系统 作者:dinner1007 时间:2019-05-31 16:57:07 0 删除 编辑
使用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不是深奥复杂的科学,但是它确实满足了常见的测量代码行间执行时间的需求。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/374079/viewspace-130852/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-08-23

  • 博文量
    1714
  • 访问量
    1477709