/*
Time a function (Rosetta code) in Picat.
http://rosettacode.org/wiki/Time_a_function
"""
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used by
the current process; instead of the difference in system time between start
and finish, which could include time used by other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting
algorithms implementations.
"""
This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com
See also my Picat page: http://www.hakank.org/picat/
*/
import util.
import cp.
main => go.
go =>
% time/1 give the time in seconds
println(time),
time(F=func(100000)),
println(F),
nl,
% time2/1 also give number of backtracks (for CP problems)
println(time2),
time2(once(queens(501,Q))),
println(Q),
nl,
% time2b/1 is a user-defined version of time2/1
time2b($once(queens(8,Q2))), % user defined version of time2/2
println(Q2),
nl,
% time3/1 show differences of all statistics
println(time3),
time3($once(queens(501,_Q3))),
% println(Q),
% show the statistics info before and after
nl,
println("statistics before:"),
statistics,
once(queens(501,_Q3)),
println("statistics after:"),
statistics,
nl.
func(N) = sum(1..N).
queens(N, Q) =>
Q=new_list(N),
Q :: 1..N,
all_different(Q),
all_different([$Q[I]-I : I in 1..N]),
all_different([$Q[I]+I : I in 1..N]),
solve([ff],Q).
% time2/1 can be defined like this
% (this is actually the original version of time2/1)
%
time2b(Goal) =>
statistics(runtime,_),
statistics(backtracks, Backtracks1),
call(Goal),
statistics(backtracks, Backtracks2),
statistics(runtime, [_,End]),
T = End / 1000.0,
Backtracks = Backtracks2 - Backtracks1,
printf("CPU time %f seconds Backtracks: %d\n", T, Backtracks).
% a more contrieved version:
% show the differences of all the statistics before / after
time3(Goal) =>
_ = statistics_all(), % reset
AllBefore = statistics_all(),
call(Goal),
AllAfter = statistics_all(),
foreach({Before,After} in zip(AllBefore,AllAfter))
Type = Before[1],
Diff = diff(Before[2],After[2]),
% println(Type=[before=Before[2],after=After[2], diff=Diff])
println(Type=Diff)
end,
nl.
% Two different versions of diff/2:
% - scalar
% - lists
diff(L1,L2) = L2 - L1, not list(L1) => true.
diff(L1,L2) = [ L2[I] - L1[I] : I in 1..L1.length], list(L1) => true.