fork download
  1. class Ideone
  2. {
  3. public static void main(String[] args)
  4. {
  5. try (Profile p = new Profile("count from 1 to 1000"))
  6. {
  7. for (int i = 0; i < 1000; ++i)
  8. {
  9. // ...
  10. }
  11. }
  12. }
  13. }
  14.  
  15. class Profile implements AutoCloseable
  16. {
  17. private final String description;
  18. private final long t0;
  19.  
  20. public Profile(String description)
  21. {
  22. this.description = description;
  23. t0 = System.nanoTime();
  24. }
  25.  
  26. @Override
  27. public void close()
  28. {
  29. long t = System.nanoTime();
  30. long elapsed = t - t0;
  31. String unit = "ns";
  32.  
  33. if (elapsed >= 10_000)
  34. {
  35. elapsed /= 1_000;
  36. unit = "µs";
  37. }
  38. if (elapsed >= 10_000)
  39. {
  40. elapsed /= 1_000;
  41. unit = "ms";
  42. }
  43. if (elapsed >= 10_000)
  44. {
  45. elapsed /= 1_000;
  46. unit = "s";
  47. }
  48. System.out.printf("%4d %s (%s)%n", elapsed, unit, description);
  49. }
  50. }
  51.  
Success #stdin #stdout 0.1s 320576KB
stdin
Standard input is empty
stdout
  21 µs (count from 1 to 1000)