Skip to content

Instantly share code, notes, and snippets.

@jdrew1303
Forked from codahale/SetBenchmark.java
Last active August 29, 2015 14:09
Show Gist options
  • Save jdrew1303/08fbd419a08be6e33488 to your computer and use it in GitHub Desktop.
Save jdrew1303/08fbd419a08be6e33488 to your computer and use it in GitHub Desktop.
<dependency>
<groupId>com.google.caliper</groupId>
<artifactId>caliper</artifactId>
<version>0.5-rc1</version>
<scope>test</scope>
</dependency>
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.HashSet;
import java.util.TreeSet;
public class SetBenchmark extends SimpleBenchmark {
// If you add a main function, you can run it from your IDE.
public static void main(String[] args) throws Exception {
new Runner().run(
// These are the command line arguments for Runner. You can add
// "--trials", "10" to run each benchmark 10 times each.
SetBenchmark.class.getName()
);
}
private static final int SET_SIZE = 100000;
// Do the up-front allocation of things in the benchmark constructor,
// just like a unit test.
private final HashSet<Integer> hash = new HashSet<Integer>(100);
private final TreeSet<Integer> tree = new TreeSet<Integer>();
// Caliper looks for methods which start with "time"; gross, I know.
// The reps argument here is injected by Caliper, which uses it to factor
// out the cost of method invocation.
public void timeHashSetAdd(int reps) {
// Be sure to add this outer loop.
for (int i = 0; i < reps; i++) {
// Then, in the inner loop, go ahead and do some meaningful work.
// Here we're seeing how long it takes to add this many integers
// to a set.
for (int j = 0; j < SET_SIZE; j++) {
hash.add(j);
}
}
}
// And now we've got a fight on our hands!
public void timeTreeSetAdd(int reps) {
for (int i = 0; i < reps; i++) {
for (int j = 0; j < 10000; j++) {
tree.add(j);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment