Skip to content

Instantly share code, notes, and snippets.

@iaveryanov
Created June 16, 2014 07:38
Show Gist options
  • Save iaveryanov/dff8800bc03fe07f9ed6 to your computer and use it in GitHub Desktop.
Save iaveryanov/dff8800bc03fe07f9ed6 to your computer and use it in GitHub Desktop.
package ru.int_overflow;
public class IntOverflowPuzzle {
// todo почему при использовании long разница в 1000 раз, действительно на столько медленнее
// todo почему при переполнении разница во времени в 1000 раз
private static void doOperation() {
// change type to long
//
// results:
// for int = 2 ms
// for long = 2366 ms
int counter = 0;
// change condition to (counter != Integer.MAX_VALUE + 1)
//
// results:
// for (counter != Integer.MAX_VALUE) = 2 ms
// for (counter != Integer.MAX_VALUE + 1) = 2378 ms
while (counter != Integer.MAX_VALUE) {
++counter;
}
}
public static void main(String[] args) {
// System.out.println("max:" + Integer.MAX_VALUE + ", min:" + Integer.MIN_VALUE);
// System.out.println((Integer.MAX_VALUE + 1) == Integer.MIN_VALUE);
for (int i = 0; i < 5; i++) {
long start = System.currentTimeMillis();
doOperation();
long intElapsed = System.currentTimeMillis() - start;
System.out.println("int: " + intElapsed + " ms");
}
//
// // extrapolation for long
// long longElapsed = Long.MAX_VALUE/Integer.MAX_VALUE * intElapsed;
// System.out.println("long: " + TimeUnit.MILLISECONDS.toDays(longElapsed) + " days");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment