Skip to content

Instantly share code, notes, and snippets.

@mclements
Created December 26, 2022 09:20
Show Gist options
  • Save mclements/b09eee918c24710f59a2eb3a6a0a7a90 to your computer and use it in GitHub Desktop.
Save mclements/b09eee918c24710f59a2eb3a6a0a7a90 to your computer and use it in GitHub Desktop.
Mercury experiment for speed and memory for summing 1..10000000
:- module test_run.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module ranges, solutions, list, int, string.
main(!IO) :-
io.command_line_arguments(Args, !IO),
((member("1", Args) -> (test1(Sum1), print_line(Sum1, !IO)))
;
(member("2", Args) -> (test2(Sum2), print_line(Sum2, !IO)))
;
(member("3", Args) -> (test3(Sum3), print_line(Sum3, !IO)))
;
(member("4", Args) -> (test4(Sum4), print_line(Sum4, !IO)))
;
(member("5", Args) -> (test5(Sum5), print_line(Sum5, !IO)))
;
print_line("select 1-4 on the command line",!IO)).
:- pred sum(int::in, int::in, int::out) is det.
sum(X,Y,Z) :- Z = X+Y.
%% foldl on a range -- fastest *and* least memory!
:- pred test1(int::out) is det.
test1(Sum) :- foldl(sum, range(1,10000000), 0, Sum). %% 0.04user 40752maxresident
%% unsorted_aggregate with promise_equivalent_solutions on nondet -- avoids creating the list and sorting
%% (3 x shortest time; low memory requirements)
:- pred test2(int::out) is det.
test2(Sum) :-
Data = (pred(I::out) is nondet :- nondet_member(I,range(1,10000000))),
promise_equivalent_solutions[Sum] (
unsorted_aggregate(Data, sum, 0, Sum)). %% 0.12user 41016maxresident
%% foldl on a specified list (6 x shortest time; 5 x least memory)
:- pred test3(int::out) is det.
test3(Sum) :- foldl(sum, 1..10000000, 0, Sum). %% 0.25user 201464maxresident
%% unsorted_solutions and foldl with promise_equivalent_solutions -- avoids sorting
%% (8 x shortest time; 5 x least memory)
:- pred test4(int::out) is det.
test4(Sum) :-
Data = (pred(I::out) is nondet :- nondet_member(I,range(1,10000000))),
promise_equivalent_solutions[List] (
unsorted_solutions(Data, List)),
foldl(sum, List, 0, Sum). %% 0.34user 201720maxresident
%% aggregate on a nondet -- creates a sorted list and then foldl
%% Given the other results: sorting a large (already sorted) list is slow
%% (150 x shortest time; 13 x least memory)
:- pred test5(int::out) is det.
test5(Sum) :-
Data = (pred(I::out) is nondet :- nondet_member(I,range(1,10000000))),
aggregate(Data, sum, 0, Sum). %% 5.81user 524312maxresident
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment