Skip to content

Instantly share code, notes, and snippets.

@tprado
Last active August 29, 2015 14:26
Show Gist options
  • Save tprado/8bbdfd6f5177ec08a7fd to your computer and use it in GitHub Desktop.
Save tprado/8bbdfd6f5177ec08a7fd to your computer and use it in GitHub Desktop.
java random spike
import java.util.Random;
public class RandomSpike {
private static final int PERCENTAGE = 50;
public static void main(String[] args) {
intNext100Example();
intNext100KExample();
doubleExample();
}
private static void intNext100Example() {
int a = 0;
int b = 0;
Random r = new Random();
long start = System.currentTimeMillis();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (r.nextInt(100) > PERCENTAGE) {
a++;
} else {
b++;
}
}
System.out.println("nextInt(100):");
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("t=" + (System.currentTimeMillis() - start));
}
private static void intNext100KExample() {
int a = 0;
int b = 0;
Random r = new Random();
long start = System.currentTimeMillis();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (r.nextInt(100000) > PERCENTAGE * 1000) {
a++;
} else {
b++;
}
}
System.out.println("nextInt(100K):");
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("t=" + (System.currentTimeMillis() - start));
}
private static void doubleExample() {
int a = 0;
int b = 0;
Random r = new Random();
long start = System.currentTimeMillis();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (r.nextDouble() > (double) PERCENTAGE / 100) {
a++;
} else {
b++;
}
}
System.out.println("nextDouble:");
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("t=" + (System.currentTimeMillis() - start));
}
}
@tprado
Copy link
Author

tprado commented Jul 27, 2015

nextInt(100):
a=1052236388
b=1095247259
t=34278

nextInt(100K):
a=1073711333
b=1073772314
t=35483

nextDouble:
a=1073733209
b=1073750438
t=65782

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment