Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DicoPerformanceTest {
- final static int NB_WORDS = 100000;
- final static int NB_LOOKUPS = 1000;
- /**
- * @param args
- */
- public static void main(String[] args) {
- IDictionary dico1 = new ArrayListDictionary();
- runExperiment("populate dico 1 (" + NB_WORDS + " words)", new
- DictionaryRandomPopulator(dico1,
- NB_WORDS));
- runExperiment("look up dico 1 (" + NB_LOOKUPS + " search)",
- new DictionaryLookupExperimenter(dico1, NB_LOOKUPS));
- }
- static void runExperiment(String name, Runnable r) {
- System.out.println("start " + name);
- long duration = System.currentTimeMillis();
- r.run();
- duration = System.currentTimeMillis() - duration;
- System.out.println(name + " executed in " + duration + " ms");
- }
- //
- // dictionary interface and implementation
- //
- static interface IDictionary {
- void put(String word, String definition);
- String getDefinition(String word);
- }
- static class ArrayListDictionary implements IDictionary {
- List<String> _wordsList = new ArrayList<String>();
- List<String> _definitionsList = new ArrayList<String>();
- @Override
- public void put(String word, String definition) {
- _wordsList.add(word);
- _definitionsList.add(definition);
- }
- @Override
- public String getDefinition(String word) {
- int index = _wordsList.indexOf(word);
- if (index >= 0) {
- _definitionsList.get(index);
- }
- // return null if word is not found in dictionary
- return null;
- }
- }
- //
- // classes for experiment
- //
- static class WordGenerator {
- public static String generate(int i) {
- return "fake_word_" + i;
- }
- public static String generateRandom(Random random) {
- return generate(random.nextInt(NB_WORDS));
- }
- }
- static class DictionaryRandomPopulator implements Runnable {
- private IDictionary _dictionary;
- private int _size;
- private Random _random = new Random(0);
- DictionaryRandomPopulator(IDictionary dictionary, int size) {
- super();
- _dictionary = dictionary;
- _size = size;
- }
- @Override
- public void run() {
- for (int i = 0; i < _size; i++) {
- _dictionary.put(WordGenerator.generate(i),
- generateDefinition(i));
- }
- }
- private String generateDefinition(int i) {
- return "fake definition for word " + i + " with random part: "
- + _random.nextInt();
- }
- }
- static class DictionaryLookupExperimenter implements Runnable {
- private IDictionary _dictionary;
- private int _number;
- private Random _random = new Random(0);
- DictionaryLookupExperimenter(IDictionary dictionary, int number) {
- super();
- _dictionary = dictionary;
- _number = number;
- }
- @Override
- public void run() {
- for (int i = 0; i < _number; i++) {
- _dictionary
- .getDefinition(WordGenerator.generateRandom(_random));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement