Skip to content

Instantly share code, notes, and snippets.

@mat
Created October 5, 2011 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mat/1265783 to your computer and use it in GitHub Desktop.
Save mat/1265783 to your computer and use it in GitHub Desktop.
How fast is it: Picking the max out of 1 Mio ints
import java.util.*;
public class HowFastIsMax {
private static final int INTEGERS_IN_LIST = 1000000;
private static final int TEST_RUNS = 10;
public static void main(String[] args) {
List<Integer> list = fillRandomIntList();
for (int i = 0; i < TEST_RUNS; i++) {
long start = System.nanoTime();
int max = searchIntListForMax(list);
long stop = System.nanoTime();
long duration = stop - start;
System.out.format("Searching %d ints for max took %fms. Max was %d.\n", list.size(), duration / 1000000.0, max);
}
}
private static List<Integer> fillRandomIntList() {
List<Integer> list = new ArrayList<Integer>(INTEGERS_IN_LIST);
Random rand = new Random();
for (int i = 0; i < INTEGERS_IN_LIST; i++) {
list.add(rand.nextInt());
}
return list;
}
private static int searchIntListForMax(List<Integer> list) {
int max = Integer.MIN_VALUE;
for (Integer i : list) {
max = i > max ? i : max;
}
return max;
}
}
//Searching 1000000 ints for max took 13.822000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.658000ms. Max was 2147479115.
//Searching 1000000 ints for max took 3.528000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.451000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.489000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.688000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.689000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.545000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.649000ms. Max was 2147479115.
//Searching 1000000 ints for max took 2.414000ms. Max was 2147479115.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment