sorting - Fast reverse sort in (SWI) Prolog -
i'm looking fast way sort list in reverse order in prolog. algorithmically should perform standard sort, options i've come slower, obvious reasons.
predicate rsort1/2
sorts , reverses.
rsort1(l1, l2) :- sort(l1, tmp), reverse(tmp, l2).
predicate rsort2/2
uses predsort/3
custom comparator.
rsort2(l1, l2) :- predsort(reverse_compare, l1, l2). reverse_compare(delta, e1, e2) :- compare(delta, e2, e1).
to test performance i've generated huge random list this:
?- size = 1234567, findall(n, (between(1, size, _), n random(size)), ns), assert(test_list(ns)). size = 1234567, ns = [183677, 351963, 737135, 246842, 22754, 1176800, 1036258|...].
these runtimes standard sort
:
?- test_list(ns), time(sort(ns, nss)). % 2 inferences, 7.550 cpu in 8.534 seconds (88% cpu, 0 lips) ns = [183677, 351963, 737135, 246842, 22754, 1176800, 1036258, 625628|...], nss = [0, 1, 3, 5, 8, 10, 12, 14, 16|...].
... rsort1
:
?- test_list(ns), time(rsort1(ns, nss)). % 779,895 inferences, 8.310 cpu in 9.011 seconds (92% cpu, 93850 lips) ns = [183677, 351963, 737135, 246842, 22754, 1176800, 1036258, 625628|...], nss = [1234564, 1234563, 1234562, 1234558, 1234557, 1234556, 1234555|...].
... , rsort2
:
?- test_list(ns), time(rsort2(ns, nss)). % 92,768,484 inferences, 67.990 cpu in 97.666 seconds (70% cpu, 1364443 lips) ns = [183677, 351963, 737135, 246842, 22754, 1176800, 1036258, 625628|...], nss = [1234564, 1234563, 1234562, 1234558, 1234557, 1234556, 1234555|...].
can better rsort1
, rsort2
speedwise?
if you're after sorting routine portable (i.e., defined using prolog), won't able implement faster (or fast, need reverse sort order) predicates execute sorting routines natively in c/c++, such sort/2
or msort/2
.
if speed of overriding concern here, of course write own non-portable predicate external definition reverse sorting. example, swi-pl c++ interface used (see examples there) write c++ definition of rsort/2
, perhaps using comparison predicates implemented in c++.
similarly, write rsort/2
in c using swi-pl c interface. src/pl-list.c
in swi-prolog source contains implementations of sorting methods (namely nat_sort()
) used sort/2
, msort/2
, keysort/2
. implement rsort/2
, might need follow implementation , tweak/reverse interpretation of calls compare()
describes standard order of terms.
Comments
Post a Comment