Skip to content

Instantly share code, notes, and snippets.

@carlosble
Created January 19, 2021 08:08
Show Gist options
  • Save carlosble/2351a9ad64adfd3a1a6b6dee5375cf3e to your computer and use it in GitHub Desktop.
Save carlosble/2351a9ad64adfd3a1a6b6dee5375cf3e to your computer and use it in GitHub Desktop.
Java benchmark
import org.junit.Test;
import java.util.Arrays;
import java.util.Objects;
import static org.assertj.core.api.Assertions.*;
public class BenchmarkTests {
static class Record implements Comparable<Record> {
private final String textField;
private final double numericField;
public Record(String textField, double numericField) {
this.textField = textField;
this.numericField = numericField;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Record)) return false;
Record record = (Record) o;
return numericField == record.numericField &&
Objects.equals(textField, record.textField);
}
@Override
public int hashCode() {
return Objects.hash(textField, numericField);
}
@Override
public int compareTo(Record record) {
return Double.compare(record.numericField, this.numericField);
}
}
@Test
public void it_iterates_very_fast_my_friend (){
int arraySize = 10000;
Record[] items = createArray(arraySize);
long timeBefore = System.currentTimeMillis();
exploreItems(items); // iteration
long timeAfter = System.currentTimeMillis();
assertThat(timeAfter - timeBefore).isLessThan(5);
// 1ms on my i7
}
@Test
public void it_sorts_very_fast_using_merge_sort (){
int arraySize = 10000;
Record[] items = createArray(arraySize);
long timeBefore = System.currentTimeMillis();
Arrays.sort(items); // mergesort
long timeAfter = System.currentTimeMillis();
assertThat(timeAfter - timeBefore).isLessThan(100);
// 50ms on my i7
}
@Test
public void it_sorts_very_fast_using_bubble_sort (){
int arraySize = 10000;
Record[] items = createArray(arraySize);
long timeBefore = System.currentTimeMillis();
bubbleSort(items);
long timeAfter = System.currentTimeMillis();
assertThat(timeAfter - timeBefore).isLessThan(1100);
// 1000ms in my i7
}
private void exploreItems(Record[] items) {
double sum = 0;
for (Record item : items) {
sum = sum + item.numericField;
}
}
private void bubbleSort(Record[] items) {
for (int i = 0; i < items.length; i++){
for (int j = 0; j < items.length -1; j++){
if (items[j].compareTo(items[j + 1]) > 0){
Record tmp = items[j];
items[j] = items[j + 1];
items[j + 1] = tmp;
}
}
}
}
private Record[] createArray(int arraySize) {
Record[] items = new Record[arraySize];
for (int i = 0; i < items.length; i++){
items[i] = initRandomRecord();
}
return items;
}
private Record initRandomRecord(){
return new Record(
String.valueOf(Math.random() * 1000), Math.random() * 1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment