Search code examples
javaperformancesortingcomparatortiming

How to time how long it takes to insert and sort separatley in a TreeMap


I would like to time how long the program takes to insert in the tree to measure the efficiency of a TreeMap's inserting. I also want to measure how long it takes to sort separately. I am doing this for a report I am writing where I am comparing the inserting time and sorting time for a TreeMap, linkedList and ArrayList. For the linkedList and ArrayList I am just going to insert all and measure first, then call list.sort(comparator) and measure how long it takes to sort. I am not sure how to do this for a TreeMap though.

final long startTime = System.currentTimeMillis();      
      Comparator<String> secondCharComparator = new Comparator<String>() {
                    @Override public int compare(String s1, String s2) {
                        return s1.substring(1, 2).compareTo(s2.substring(1, 2));
                    }           
                };

        SortedMap<String,String> map =
                new TreeMap<String,String>(secondCharComparator);
            map.put("a", "one");
            map.put("a", "two");
            map.put("cd", "three");
    final long endTime = System.currentTimeMillis();

long totalTime = endTime - startTime;

Solution

  • If your data structure is "sorted" by default; than there is no point in measuring the time it needs for "sorting".

    The only thing you can do is: measure how long it takes to INSERT + SORT your lists; then measure how long it takes to INSERT into your TreeMap.

    Side note: you understand that you might want to use much more data? And that your data sets should have different properties (it can make a huge difference for example if the elements you are inserting/sorting ... have a random distribution, are partially sorted, reverse sorted, ... )