Examples of smaller Java programs that do various interesting things.

Stopwatch.java 827B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. A class to measure time elapsed.
  3. */
  4. public class Stopwatch
  5. {
  6. private long startTime;
  7. private long stopTime;
  8. public static final double NANOS_PER_SEC = 1000000000.0;
  9. /**
  10. start the stop watch.
  11. */
  12. public void start(){
  13. startTime = System.nanoTime();
  14. }
  15. /**
  16. stop the stop watch.
  17. */
  18. public void stop()
  19. { stopTime = System.nanoTime(); }
  20. /**
  21. elapsed time in seconds.
  22. @return the time recorded on the stopwatch in seconds
  23. */
  24. public double time()
  25. { return (stopTime - startTime) / NANOS_PER_SEC; }
  26. public String toString(){
  27. return "elapsed time: " + time() + " seconds.";
  28. }
  29. /**
  30. elapsed time in nanoseconds.
  31. @return the time recorded on the stopwatch in nanoseconds
  32. */
  33. public long timeInNanoseconds()
  34. { return (stopTime - startTime); }
  35. }