fork download
  1.  
  2. import java.util.concurrent.TimeUnit;
  3. import java.util.concurrent.atomic.AtomicLong;
  4.  
  5.  
  6. class Ideone {
  7. public static void main(String[] args) {
  8. final int n = 100;
  9. final int k = 100000;
  10. long elap;
  11.  
  12. elap = 0;
  13. for (int i = 0; i < n; i++) {
  14. elap += testPlain(k);
  15. }
  16. System.out.printf("for (1 .. %d) { for (1 .. %d) <count with %s> }: avg=%d (total=%d) in millis%n", n, k, "+=", TimeUnit.MILLISECONDS.convert(elap / n, TimeUnit.NANOSECONDS), TimeUnit.MILLISECONDS.convert(elap, TimeUnit.NANOSECONDS));
  17.  
  18. elap = 0;
  19. for (int i = 0; i < n; i++) {
  20. elap += testSynchronized(k);
  21. }
  22. System.out.printf("for (1 .. %d) { for (1 .. %d) <count with %s> }: avg=%d (total=%d) in millis%n", n, k, "synchronized(+=)", TimeUnit.MILLISECONDS.convert(elap / n, TimeUnit.NANOSECONDS), TimeUnit.MILLISECONDS.convert(elap, TimeUnit.NANOSECONDS));
  23.  
  24. elap = 0;
  25. for (int i = 0; i < n; i++) {
  26. elap += testAtomicLong(k);
  27. }
  28. System.out.printf("for (1 .. %d) { for (1 .. %d) <count with %s> }: avg=%d (total=%d) in millis%n", n, k, "AtomicLong#addAndGet", TimeUnit.MILLISECONDS.convert(elap / n, TimeUnit.NANOSECONDS), TimeUnit.MILLISECONDS.convert(elap, TimeUnit.NANOSECONDS));
  29. }
  30.  
  31. static void nullmethod(final long l) {
  32.  
  33. }
  34.  
  35. static long testPlain(final int n) {
  36. final long begin = System.nanoTime();
  37. long sum = 0;
  38. for (int i = 0; i < n; i++) {
  39. sum += i;
  40. }
  41. nullmethod(sum);
  42. return System.nanoTime() - begin;
  43. }
  44.  
  45. static long testSynchronized(final int n) {
  46. final long begin = System.nanoTime();
  47. long sum = 0;
  48. for (int i = 0; i < n; i++) {
  49. synchronized (Ideone.class) {
  50. sum += i;
  51. }
  52. }
  53. nullmethod(sum);
  54. return System.nanoTime() - begin;
  55. }
  56.  
  57. static long testAtomicLong(final int n) {
  58. final long begin = System.nanoTime();
  59. AtomicLong sum = new AtomicLong();
  60. for (int i = 0; i < n; i++) {
  61. sum.addAndGet(i);
  62. }
  63. nullmethod(sum.get());
  64. return System.nanoTime() - begin;
  65. }
  66.  
  67. }
  68.  
Success #stdin #stdout 0.5s 380224KB
stdin
Standard input is empty
stdout
for (1 .. 100) { for (1 .. 100000) <count with +=> }: avg=0 (total=18) in millis
for (1 .. 100) { for (1 .. 100000) <count with synchronized(+=)> }: avg=2 (total=249) in millis
for (1 .. 100) { for (1 .. 100000) <count with AtomicLong#addAndGet> }: avg=1 (total=165) in millis