/bench/kilim/bench/Ex_vs_Ret.java

http://github.com/kilim/kilim · Java · 65 lines · 46 code · 10 blank · 9 comment · 8 complexity · b9f34f2f1450047e996476ad81e85813 MD5 · raw file

  1. /* Copyright (c) 2006, Sriram Srinivasan
  2. *
  3. * You may distribute this software under the terms of the license
  4. * specified in the file "License"
  5. */
  6. package kilim.bench;
  7. public class Ex_vs_Ret {
  8. /**
  9. * @param args
  10. */
  11. public static void main(String[] args) {
  12. final int ntimes = 1000000;
  13. final int depth = 10;
  14. // JIT Warmup ===========================================
  15. for (int i = 0; i < 1000; i++) ret(depth);
  16. for (int i = 0; i < 1000; i++) {
  17. try {
  18. ex(depth);
  19. } catch (FastEx ignore) {}
  20. }
  21. long start = System.currentTimeMillis();
  22. for (int i = 0; i < ntimes; i++) {
  23. ret(depth);
  24. }
  25. long elapsed = System.currentTimeMillis() - start;
  26. System.out.println("Iterations = : " +ntimes + ", stack depth = " + depth);
  27. System.out.println("ret ms: " + elapsed);
  28. start = System.currentTimeMillis();
  29. for (int i = 0; i < ntimes; i++) {
  30. try {
  31. ex(depth);
  32. } catch (FastEx fe) {}
  33. }
  34. elapsed = System.currentTimeMillis() - start;
  35. System.out.println("ex : " + elapsed);
  36. }
  37. static void ret(int depth) {
  38. if (depth != 0) {
  39. ret(depth-1);
  40. }
  41. }
  42. static void ex(int depth) throws FastEx {
  43. if (depth == 0) {
  44. throw new FastEx();
  45. }
  46. ex(depth-1);
  47. }
  48. }
  49. final class FastEx extends Throwable {
  50. private static final long serialVersionUID = 1L; // Just suppressing warnings.
  51. @Override
  52. public synchronized Throwable fillInStackTrace() {
  53. return null; // The most time consuming part of throwing an exception.
  54. }
  55. }