Compare sorting algorithms' performance

From Rosetta Code
Revision as of 17:12, 13 November 2009 by A (talk | contribs) (→‎ones: diminished thumbnail width)
Task
Compare sorting algorithms' performance
You are encouraged to solve this task according to the task description, using any language you may know.

Measure a relative performance of sorting algorithms implementations.

Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures).

Consider three type of input sequences:

  • ones: sequence of all 1's. Example: {1, 1, 1, 1, 1}
  • range: ascending sequence, i.e. already sorted. Example: {1, 2, 3, 10, 15}
  • shuffled range: sequence with elements randomly distributed. Example: {5, 3, 9, 6, 8}

Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms. Where possible, use existing implementations.

Preliminary subtask:

General steps:

  1. Define sorting routines to be considered.
  2. Define appropriate sequence generators and write timings.
  3. Plot timings.
  4. What conclusions about relative performance of the sorting routines could be made based on the plots?

C

(The reference example is Python)

Examples of sorting routines

We can use the codes in the category Sorting Algorithms; since these codes deal with integer arrays, we should change them a little. To accomplish this task I've also renamed them more consistently algorithm_sort; so we have e.g. bubble_sort, quick_sort and so on.

Sequence generators

csequence.h <lang c>#ifndef _CSEQUENCE_H

  1. define _CSEQUENCE_H
  2. include <stdlib.h>

void setfillconst(double c); void fillwithconst(double *v, int n); void fillwithrrange(double *v, int n); void shuffledrange(double *v, int n);

  1. endif</lang>

csequence.c <lang c>#include "csequence.h"

static double fill_constant;

void setfillconst(double c) {

 fill_constant = c;

}

void fillwithconst(double *v, int n) {

 while( --n >= 0 ) v[n] = fill_constant;

}

void fillwithrrange(double *v, int n) {

 int on = n;
 while( --on >= 0 ) v[on] = n - on;

}

void shuffledrange(double *v, int n) {

 int on = n;
 fillwithrrange(v, n);
 while( --n >= 0 ) {
   int r = rand() % on;
   double t = v[n];
   v[n] = v[r];
   v[r] = t;
 }

}</lang>

Write timings

We shall use the code from Query Performance. Since the action is a generic function with a single argument, we need wrappers which encapsule each sorting algorithms we want to test.

writetimings.h <lang c>#ifndef _WRITETIMINGS_H

  1. define _WRITETIMINGS_H
  2. include "sorts.h"
  3. include "csequence.h"
  4. include "timeit.h"

/* we repeat the same MEANREPEAT times, and get the mean; this *should*

  give "better" results ... */
  1. define MEANREPEAT 10.0
  2. define BUFLEN 128
  3. define MAKEACTION(ALGO) \
 int action_ ## ALGO (int size) {				\
   ALGO ## _sort(tobesorted, size);				\
   return 0; }
  1. define MAKEPIECE(N) { #N , action_ ## N }

int action_bubble(int size); int action_shell(int size); int action_quick(int size); int action_insertion(int size); int action_merge(int size); int doublecompare( const void *a, const void *b ); int action_qsort(int size); int get_the_longest(int *a);

struct testpiece {

 const char *name;
 int (*action)(int);

}; typedef struct testpiece testpiece_t;

struct seqdef {

 const char *name;
 void (*seqcreator)(double *, int);

}; typedef struct seqdef seqdef_t;

  1. endif</lang>

writetimings.c <lang c>#include <stdio.h>

  1. include <stdlib.h>
  1. include "writetimings.h"

double *tobesorted = NULL; const char *bname = "data_"; const char *filetempl = "%s%s_%s.dat"; int datlengths[] = {100, 200, 300, 500, 1000, 5000, 10000, 50000, 100000};

testpiece_t testpieces[] = { // MAKEPIECE(bubble),

 MAKEPIECE(shell),
 MAKEPIECE(merge),
 MAKEPIECE(insertion),
 MAKEPIECE(quick),
 MAKEPIECE(qsort),
 { NULL, NULL }

};

seqdef_t seqdefs[] = {

 { "c1", fillwithconst },
 { "rr", fillwithrrange },
 { "sr", shuffledrange },
 { NULL, NULL }

};


MAKEACTION(bubble) MAKEACTION(insertion) MAKEACTION(quick) MAKEACTION(shell)

int action_merge(int size) {

 double *res = merge_sort(tobesorted, size);
 free(res); /* unluckly this affects performance */
 return 0;

}

int doublecompare( const void *a, const void *b ) {

 if ( *(double *)a == *(double *)b ) return 0;
 if ( *(double *)a < *(double *)b ) return -1; else return 1;

} int action_qsort(int size) {

 qsort(tobesorted, size, sizeof(double), doublecompare);
 return 0;

}

int get_the_longest(int *a) {

 int r = *a;
 while( *a > 0 ) {
   if ( *a > r ) r = *a;
   a++;
 }
 return r;

}


int main() {

 int i, j, k, z, lenmax;
 char buf[BUFLEN];
 FILE *out;
 double thetime;
 lenmax = get_the_longest(datlengths);
 printf("Bigger data set has %d elements\n", lenmax);
 tobesorted = malloc(sizeof(double)*lenmax);
 if ( tobesorted == NULL ) return 1;
 setfillconst(1.0);
 for(i=0; testpieces[i].name != NULL; i++) {
   for(j=0; seqdefs[j].name != NULL; j++) {
     snprintf(buf, BUFLEN, filetempl, bname, testpieces[i].name,

seqdefs[j].name);

     out = fopen(buf, "w");
     if ( out == NULL ) goto severe;
     printf("Producing data for sort '%s', created data type '%s'\n", 

testpieces[i].name, seqdefs[j].name);

     for(k=0; datlengths[k] > 0; k++) {

printf("\tNumber of elements: %d\n", datlengths[k]); thetime = 0.0; seqdefs[j].seqcreator(tobesorted, datlengths[k]); fprintf(out, "%d ", datlengths[k]); for(z=0; z < MEANREPEAT; z++) { thetime += time_it(testpieces[i].action, datlengths[k]); } thetime /= MEANREPEAT; fprintf(out, "%.8lf\n", thetime);

     }
     fclose(out);
   }
 }

severe:

 free(tobesorted);
 return 0;

}</lang> This code produce several files with the following naming convention:

  • data_algorithm_sequence.dat

Where algorithm is one of the following: insertion, merge, shell, quick, qsort (the quicksort in the libc library) (bubble sort became too slow for longest sequences). Sequence is c1 (constant value 1), rr (reverse range), sr (shufled range). These data can be easily plotted by Gnuplot, which can also do fitting. Instead we do our fitting using Polynomial Fitting. <lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <math.h>
  1. include "polifitgsl.h"
  1. define MAXNUMOFDATA 100

double x[MAXNUMOFDATA], y[MAXNUMOFDATA]; double cf[2];

int main() {

 int i, nod;
 int r;
 for(i=0; i < MAXNUMOFDATA; i++)
 {
   r = scanf("%lf %lf\n", &x[i], &y[i]);
   if ( (r == EOF) || (r < 2) ) break;
   x[i] = log10(x[i]);
   y[i] = log10(y[i]);
 }
 nod = i;
 polynomialfit(nod, 2, x, y, cf);
 printf("C0 = %lf\nC1 = %lf\n", cf[0], cf[1]);
 return 0;

}</lang> Here we search for a fit with C0+C1x "in the log scale", since we supposed the data, once plotted on a logscale graph, can be fitted by a line. We can use e.g. a shell one-liner to produce the parameters for the line for each data file previously output. In particular I've used the following

for el in *.dat ; do fitdata <$el >${el%.dat}.fd ; done

Plot timings and Figures

Once we have all the ".dat" files and associated ".fd", we can use Gnuplot to draw our data and think about conclusions (we could also use the idea in Plot x, y arrays, but it needs too much enhancements to be usable for this analysis). Here an example of such a draw for a single file (using Gnuplot)

gnuplot> f(x) = C0 + C1*x
gnuplot> set logscale xy
gnuplot> load 'data_quick_sr_u.fd'
gnuplot> set xrange [100:100000]
gnuplot> set key left
gnuplot> plot 10**f(log10(x)), 'data_quick_sr_u.dat'

(The _u.dat are produced by a modified version of the code in order to write timings in microseconds instead of seconds) We can easily write another shell script/one-liner to produce a single file driver for Gnuplot in order to produce all the graph we can be interested in. These graphs show that the linear (in log scale) fit do not always fit the data... I haven't repeated the tests; the problems are when the sequence length becomes huge; for some algorithm that uses extra memory (like implementation of the merge sort), this could depend on the allocation of the needed memory. Another extraneous factor could be system load (the CLOCK_MONOTONIC used by the timing function is system wide rather than per process, so counting time spent in other processes too?). The "most stable" algorithms seem to be quick sort (but not qsort, which indeed is just the libc quick sort, here not plotted!) and shell sort (except for reversed range).

Conclusion: we should repeat the tests...

Python

Works with: Python version 2.5

Examples of sorting routines

<lang python> def builtinsort(x):

    x.sort()
def partition(seq, pivot):
   low, middle, up = [], [], []
   for x in seq:
       if x < pivot:
           low.append(x)
       elif x == pivot:
           middle.append(x)
       else:
           up.append(x)
   return low, middle, up
import random
def qsortranpart(seq):
   size = len(seq)
   if size < 2: return seq
   low, middle, up = partition(seq, random.choice(seq))
   return qsortranpart(low) + middle + qsortranpart(up)</lang>

Sequence generators

<lang python> def ones(n):

    return [1]*n
def reversedrange(n):
    return reversed(range(n))
def shuffledrange(n):
    x = range(n)
    random.shuffle(x)
    return x</lang>    

Write timings

<lang python> def write_timings(npoints=10, maxN=10**4, sort_functions=(builtinsort,insertion_sort, qsort),

                  sequence_creators = (ones, range, shuffledrange)):    
   Ns = range(2, maxN, maxN//npoints)
   for sort in sort_functions:
       for make_seq in sequence_creators:
           Ts = [usec(sort, (make_seq(n),)) for n in Ns]
           writedat('%s-%s-%d-%d.xy' % (sort.__name__,  make_seq.__name__, len(Ns), max(Ns)), Ns, Ts)</lang>

Where writedat() is defined in the Write float arrays to a text file, usec() - Query Performance, insertion_sort() - Insertion sort, qsort - Quicksort subtasks, correspondingly.

Plot timings

Library: matplotlib
Library: numpy

<lang python> import operator

import numpy, pylab
def plotdd(dictplotdict):
   """See ``plot_timings()`` below."""
   symbols = ('o', '^', 'v', '<', '>', 's', '+', 'x', 'D', 'd',
              '1', '2', '3', '4', 'h', 'H', 'p', '|', '_')
   colors = list('bgrcmyk') # split string on distinct characters
   for npoints, plotdict in dictplotdict.iteritems():
       for ttle, lst in plotdict.iteritems():            
           pylab.hold(False)                                
           for i, (label, polynom, x, y) in enumerate(sorted(lst,key=operator.itemgetter(0))):
               pylab.plot(x, y, colors[i % len(colors)] + symbols[i % len(symbols)], label='%s %s' % (polynom, label))
               pylab.hold(True)
               y = numpy.polyval(polynom, x)
               pylab.plot(x, y, colors[i % len(colors)], label= '_nolegend_')                
           pylab.legend(loc='upper left')
           pylab.xlabel(polynom.variable)
           pylab.ylabel('log2( time in microseconds )')                
           pylab.title(ttle, verticalalignment='bottom')
           figname = '_%(npoints)03d%(ttle)s' % vars()
           pylab.savefig(figname+'.png')
           pylab.savefig(figname+'.pdf')
           print figname</lang>

See Plot x, y arrays and Polynomial Fitting subtasks for a basic usage of pylab.plot() and numpy.polyfit().

<lang python> import collections, itertools, glob, re

import numpy
def plot_timings():
   makedict = lambda: collections.defaultdict(lambda: collections.defaultdict(list))
   df = makedict()
   ds = makedict()
   # populate plot dictionaries
   for filename in glob.glob('*.xy'):
       m = re.match(r'([^-]+)-([^-]+)-(\d+)-(\d+)\.xy', filename)
       print filename
       assert m, filename
       funcname, seqname, npoints, maxN = m.groups()
       npoints, maxN = int(npoints), int(maxN)        
       a = numpy.fromiter(itertools.imap(float, open(filename).read().split()), dtype='f')
       Ns = a[::2]  # sequences lengths
       Ts = a[1::2] # corresponding times 
       assert len(Ns) == len(Ts) == npoints
       assert max(Ns) <= maxN
       #
       logsafe = numpy.logical_and(Ns>0, Ts>0)
       Ts = numpy.log2(Ts[logsafe])
       Ns = numpy.log2(Ns[logsafe])
       coeffs = numpy.polyfit(Ns, Ts, deg=1)
       poly = numpy.poly1d(coeffs, variable='log2(N)')
       #
       df[npoints][funcname].append((seqname, poly, Ns, Ts))
       ds[npoints][seqname].append((funcname, poly, Ns, Ts))
   # actual plotting
   plotdd(df)
   plotdd(ds) # see ``plotdd()`` above</lang>

Figures: log2( time in microseconds ) vs. log2( sequence length )

<lang python> sort_functions = [

    builtinsort,         # see implementation above
    insertion_sort,      # see Insertion sort
    insertion_sort_lowb, # insertion_sort, where sequential search is replaced
                         #     by lower_bound() function
    qsort,               # see Quicksort
    qsortranlc,          # qsort with randomly choosen pivot
                         #     and the filtering via list comprehension
    qsortranpart,        # qsortranlc with filtering via partition function
    qsortranpartis,      # qsortranpart, where for a small input sequence lengths
    ]                    #     insertion_sort is called
if __name__=="__main__":
   import sys
   sys.setrecursionlimit(10000)
   write_timings(npoints=100, maxN=1024, # 1 <= N <= 2**10 an input sequence length
                 sort_functions=sort_functions,
                 sequence_creators = (ones, range, shuffledrange))
   plot_timings()</lang>

Executing above script we get belowed figures.

ones

log(Time) vs. log(N): Relative performance on [1]*N as an input

ones.png (143KiB)

builtinsort     - O(N)
insertion_sort  - O(N)
qsort           - O(N**2)
qsortranpart    - O(N)

range

log(Time) vs. log(N): Relative performance on range(N) as an input

range.png (145KiB)

builtinsort     - O(N)
insertion_sort  - O(N)
qsort           - O(N**2)
qsortranpart    - O(N*log(N))

shuffled range

log(Time) vs. log(N): Relative performance on random permutation of range(N) as an input

shuffledrange.png (152KiB)

builtinsort     - O(N)  
insertion_sort  - O(N**4) ???
qsort           - O(N*log(N))
qsortranpart    - O(N) ???

Tcl

Background

The lsort command is Tcl's built-in sorting engine. It is implemented in C as a mergesort, so while it is theoretically slower than quicksort, it is a stable sorting algorithm too, which produces results that tend to be less surprising in practice. This task will be matching it against multiple manually-implemented sorting procedures.

Code

Library: Tk
Library: tcllib

<lang tcl>###############################################################################

  1. measure and plot times

package require Tk package require struct::list namespace path ::tcl::mathfunc

proc create_log10_plot {title xlabel ylabel xs ys labels shapes colours} {

   set w [toplevel .[clock clicks]]
   wm title $w $title
   pack [canvas $w.c -background white]
   pack [canvas $w.legend -background white]
   update
   plot_log10 $w.c $w.legend $title $xlabel $ylabel $xs $ys $labels $shapes $colours
   $w.c config -scrollregion [$w.c bbox all]
   update

}

proc plot_log10 {canvas legend title xlabel ylabel xs ys labels shapes colours} {

   global xfac yfac
   set log10_xs [map {_ {log10 $_}} $xs]
   foreach series $ys {
       lappend log10_ys [map {_ {log10 $_}} $series]
   }
   set maxx [max {*}$log10_xs]
   set yvalues [lsort -real [struct::list flatten $log10_ys]]
   set firstInf [lsearch $yvalues Inf]
   set maxy [lindex $yvalues [expr {$firstInf == -1 ? [llength $yvalues] - 1 : $firstInf - 1}]]
   set xfac [expr {[winfo width $canvas] * 0.8/$maxx}]
   set yfac [expr {[winfo height $canvas] * 0.8/$maxy}]
   scale $canvas x 0 $maxx $xfac "log10($xlabel)"
   scale $canvas y 0 $maxy $yfac "log10($ylabel)"
   $legend create text 30 0 -text $title -anchor nw
   set count 1
   foreach series $log10_ys shape $shapes colour $colours label $labels {
       plotxy $canvas $log10_xs $series $shape $colour
       legenditem $legend [incr count] $shape $colour $label
   }

}

proc map {lambda list} {

   set res [list]
   foreach item $list {lappend res [apply $lambda $item]}
   return $res

}

proc legenditem {legend pos shape colour label} {

   set y [expr {$pos * 15}]
   $shape $legend 20 $y -fill $colour
   $legend create text 30 $y -text $label -anchor w

}

  1. The actual plotting engine

proc plotxy {canvas _xs _ys shape colour} {

   global xfac yfac
   foreach x $_xs y $_ys {
       if {$y < Inf} {
           lappend xs $x
           lappend ys $y
       }
   }
   set coords [list]
   foreach x $xs y $ys {
       set coord_x [expr {$x*$xfac}]
       set coord_y [expr {-$y*$yfac}]
       $shape $canvas $coord_x $coord_y -fill $colour
       lappend coords $coord_x $coord_y
   }
   $canvas create line $coords -smooth true

}

  1. Rescales the contents of the given canvas

proc scale {canvas direction from to fac label} {

   set f [expr {$from*$fac}]
   set t [expr {$to*$fac}]
   switch -- $direction {
       x {
           set f [expr {$from * $fac}]
           set t [expr {$to * $fac}]
           $canvas create line $f 0 $t 0
           $canvas create text $f 0 -anchor nw -text $from
           $canvas create text $t 0 -anchor n -text [format "%.1f" $to]
           $canvas create text [expr {($f+$t)/2}] 0 -anchor n -text $label
       }
       y {
           set f [expr {$from * -$fac}]
           set t [expr {$to * -$fac}]
           $canvas create line 0 $f 0 $t
           $canvas create text 0 $f -anchor se -text $from
           $canvas create text 0 $t -anchor e -text [format "%.1f" $to]
           $canvas create text 0 [expr {($f+$t)/2}] -anchor e -text $label
       }
   }

}

  1. Helper to make points, which are otherwise not a native item type

proc dot {canvas x y args} {

   set id [$canvas create oval [expr {$x-3}] [expr {$y-3}] \
               [expr {$x+3}] [expr {$y+3}]]
   $canvas itemconfigure $id {*}$args

} proc square {canvas x y args} {

   set id [$canvas create rectangle [expr {$x-3}] [expr {$y-3}] \
               [expr {$x+3}] [expr {$y+3}]]
   $canvas itemconfigure $id {*}$args

} proc cross {canvas x y args} {

   set l1 [$canvas create line [expr {$x-3}] $y [expr {$x+3}] $y]
   set l2 [$canvas create line $x [expr {$y-3}] $x [expr {$y+3}]]
   $canvas itemconfigure $l1 {*}$args
   $canvas itemconfigure $l2 {*}$args

} proc triangleup {canvas x y args} {

   set id [$canvas create polygon $x [expr {$y-4}] \
               [expr {$x+4}] [expr {$y+4}] \
               [expr {$x-4}] [expr {$y+4}]]
   $canvas itemconfigure $id {*}$args

} proc triangledown {canvas x y args} {

   set id [$canvas create polygon $x [expr {$y+4}] \
               [expr {$x+4}] [expr {$y-4}] \
               [expr {$x-4}] [expr {$y-4}]]
   $canvas itemconfigure $id {*}$args

}

wm withdraw .

  1. list creation procedures

proc ones n {

   lrepeat $n 1

} proc reversed n {

   while {[incr n -1] >= 0} {
       lappend result $n
   }
   return $result

} proc random n {

   for {set i 0} {$i < $n} {incr i} {
       lappend result [expr {int($n * rand())}]
   }
   return $result

}

set algorithms {lsort quicksort shellsort insertionsort bubblesort} set sizes {1 10 100 1000 10000 100000} set types {ones reversed random} set shapes {dot square cross triangleup triangledown} set colours {red blue black brown yellow}

  1. create some lists to be used by all sorting algorithms

array set lists {} foreach size $sizes {

   foreach type $types {
       set lists($type,$size) [$type $size]
   }

}

set runs 10

  1. header

fconfigure stdout -buffering none puts -nonewline [format "%-16s" "list length:"] foreach size $sizes {

   puts -nonewline [format " %10d" $size]

} puts ""

  1. perform the sort timings and output results

foreach type $types {

   puts "\nlist type: $type"
   set times [list]
   foreach algo $algorithms {
       set errs [list]
       set thesetimes [list]
       $algo {} ;# call it once to ensure it's compiled
       
       puts -nonewline [format "   %-13s" $algo]
       foreach size $sizes {
           # some implementations are just too slow
           if {$type ne "ones" && (
               ($algo eq "insertionsort" && $size > 10000) ||
               ($algo eq "bubblesort" && $size > 1000))
           } {
               set time Inf
           } else {
               # OK, do it
               if {[catch {time [list $algo $lists($type,$size)] $runs} result] != 0} {
                   set time Inf
                   lappend errs $result
               } else {
                   set time [lindex [split $result] 0]
               }
           }
           lappend thesetimes $time
           puts -nonewline [format " %10s" $time]
       }
       puts ""
       if {[llength $errs] > 0} {
           puts [format "      %s" [join $errs "\n      "]]
       }
       lappend times $thesetimes
   }
   create_log10_plot "Sorting a '$type' list" size time $sizes $times $algorithms $shapes $colours

} puts "\ntimes in microseconds, average of $runs runs"</lang>

Output

list length:              1         10        100       1000      10000     100000

list type: ones
   lsort                0.9        1.3        7.2       76.4     1029.8    12366.2
   quicksort            1.1        8.3      327.7      363.8     4331.8    40078.0
   shellsort            1.6       15.9      237.5     4681.6    59656.3   718282.9
   insertionsort        1.0        6.7       55.6      580.6     5197.0    53521.2
   bubblesort           1.9        5.2       34.5      471.0     3186.1    32618.6

list type: reversed
   lsort                1.1        1.6       10.2      118.5     1559.1    19793.2
   quicksort            1.3       41.6      625.3     6522.4    79919.3   966666.2
   shellsort            1.6       26.7      431.5     6636.4    95542.4  1195338.0
   insertionsort        1.3       46.6     1654.7   156844.2 15697445.8        Inf
   bubblesort           1.9      447.0    46347.3  4682981.4        Inf        Inf

list type: random
   lsort                1.2        1.7       15.2      221.6     3347.4    54915.9
   quicksort            1.3       33.7      425.4     5438.9    71233.6   918698.5
   shellsort            1.4       24.1      584.8     9095.8   137090.1  2259131.9
   insertionsort        1.4       11.7      879.2    78187.1  7920941.8        Inf
   bubblesort           1.9      146.6    25097.6  2434040.7        Inf        Inf

times in microseconds, average of 10 runs