/ocr/ocrservice/src/com/googlecode/eyesfree/env/Stopwatch.java

http://eyes-free.googlecode.com/ · Java · 86 lines · 51 code · 14 blank · 21 comment · 5 complexity · 003920f2204287a00d4d6dd0785beb84 MD5 · raw file

  1. /*
  2. * Copyright (C) 2011 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.googlecode.eyesfree.env;
  17. import android.os.SystemClock;
  18. /**
  19. * An interval timing class. This class does not count time while the device
  20. * is in deep sleep.
  21. *
  22. * @author Sharvil Nanavati
  23. */
  24. public class Stopwatch {
  25. private final String name;
  26. private long startTime;
  27. private long totalTime;
  28. private boolean isRunning;
  29. public Stopwatch() {
  30. name = null;
  31. }
  32. public Stopwatch(String name) {
  33. this.name = name;
  34. }
  35. public void start() {
  36. if (isRunning) {
  37. return;
  38. }
  39. startTime = SystemClock.uptimeMillis();
  40. isRunning = true;
  41. }
  42. public void stop() {
  43. if (!isRunning) {
  44. return;
  45. }
  46. long now = SystemClock.uptimeMillis();
  47. totalTime += (now - startTime);
  48. isRunning = false;
  49. }
  50. public void reset() {
  51. startTime = SystemClock.uptimeMillis();
  52. totalTime = 0;
  53. }
  54. public boolean isRunning() {
  55. return isRunning;
  56. }
  57. public long getElapsedMilliseconds() {
  58. if (isRunning) {
  59. long now = SystemClock.uptimeMillis();
  60. totalTime += (now - startTime);
  61. startTime = now;
  62. }
  63. return totalTime;
  64. }
  65. @Override
  66. public String toString() {
  67. if (name != null) {
  68. return "[" + name + ": " + totalTime + "ms]";
  69. }
  70. return totalTime + "ms";
  71. }
  72. }