Skip to content

Instantly share code, notes, and snippets.

@thomaslee
Last active August 29, 2015 13:56
Show Gist options
  • Save thomaslee/8819932 to your computer and use it in GitHub Desktop.
Save thomaslee/8819932 to your computer and use it in GitHub Desktop.
public class Main {
public static void main(final String[] args) {
final long[] values = new long[250000];
final Random random = new Random();
for (int i = 0; i < 250000; i++) {
values[i] = random.nextLong();
}
final Derived1 derived1 = new Derived1();
final Derived2 derived2 = new Derived2();
final Derived3 derived3 = new Derived3();
System.out.println("Java v" + System.getProperty("java.runtime.version"));
//
// monomorphic case using derived1 only
//
benchmark1("monomorphic (1)", derived1, values);
benchmark1("monomorphic (2)", derived1, values);
benchmark1("monomorphic (3)", derived1, values);
//
// first call using derived2 makes base.accumulate(...) call site in benchmark1 bimorphic
//
benchmark1("bimorphic (1)", derived2, values);
benchmark1("bimorphic (2)", derived1, values);
benchmark1("bimorphic (3)", derived2, values);
//
// call using derived3 makes base.accumulate(...) call site in benchmark1 megamorphic
//
benchmark1("megamorphic (1)", derived3, values);
benchmark1("megamorphic (2)", derived2, values);
benchmark1("megamorphic (3)", derived1, values);
//
// monomorphic case at a different call site
//
benchmark2("monomorphic (call site 2)", derived3, values);
}
private static void benchmark1(final String name, final Base base, final long[] values) {
final long iterations = values.length * 1000l;
System.out.print(MessageFormat.format("{0} {1} calls: ", iterations, name));
final long before = System.currentTimeMillis();
for (long i = 0; i < iterations; i++) {
base.accumulate(values[(int) (i % values.length)]);
}
final long result = System.currentTimeMillis() - before;
System.out.println(MessageFormat.format("{0}", result));
}
//
// copy/paste of benchmark1 to show *morphisms are specific to a particular call site
//
private static void benchmark2(final String name, final Base base, final long[] values) {
final long iterations = values.length * 1000l;
System.out.print(MessageFormat.format("{0} {1} calls: ", iterations, name));
final long before = System.currentTimeMillis();
for (long i = 0; i < iterations; i++) {
base.accumulate(values[(int) (i % values.length)]);
}
final long result = System.currentTimeMillis() - before;
System.out.println(MessageFormat.format("{0}", result));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment