Skip to content

Instantly share code, notes, and snippets.

@moznion
Created March 24, 2015 04:20
Show Gist options
  • Save moznion/508bd516e0c547e79d29 to your computer and use it in GitHub Desktop.
Save moznion/508bd516e0c547e79d29 to your computer and use it in GitHub Desktop.
package net.moznion;
import me.geso.nanobench.Benchmark;
import me.geso.nanobench.Benchmark.Bench;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class BenchmarkRandom {
public static class RandomNumberGenerator extends Thread {
private static final Random RANDOM = new Random();
@Override
public void run() {
RANDOM.nextDouble();
}
}
public static class ThreadLocalRandomNumberGenerator extends Thread {
@Override
public void run() {
ThreadLocalRandom.current().nextDouble();
}
}
@Bench
public void withRandom() throws InstantiationException, IllegalAccessException {
runThreads(RandomNumberGenerator.class);
}
@Bench
public void withThreadLocalRandom() throws InstantiationException, IllegalAccessException {
runThreads(ThreadLocalRandomNumberGenerator.class);
}
private <E extends Thread> void runThreads(Class<E> threadClass)
throws InstantiationException, IllegalAccessException {
for (int i = 0; i < 1000; i++) {
threadClass.newInstance().start();
}
}
public static void main(String[] args) throws Exception {
new Benchmark(new App()).warmup(10).run(1000).timethese().cmpthese();
}
}
@moznion
Copy link
Author

moznion commented Mar 24, 2015

Score:

withRandom: 52 wallclock secs (18.70 usr + 24.70 sys = 43.39 CPU) @ 23.05/s (n=1000)
withThreadLocalRandom: 52 wallclock secs (18.27 usr + 24.81 sys = 43.08 CPU) @ 23.21/s (n=1000)

Comparison chart:

                           Rate  withRandom  withThreadLocalRandom
             withRandom  23.0/s          --                    -1%
  withThreadLocalRandom  23.2/s          1%                     --

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