1/*  pl2detlog_bench.pl -- runs a query in a fresh process for pl2detlog_compile/2:
    2    its answer and output once, then its time per run.
    3*/
    4:- module(pl2detlog_bench, [bench/4]).    5
    6bench(File, GoalText, ResultFile, Budget) :-
    7    file_directory_name(File, Dir),
    8    working_directory(_, Dir),
    9    catch_halt,
   10    (   catch(load_files(user:File, [silent(true)]), E, true), var(E)
   11    ->  term_string(G, GoalText, [module(user)]),
   12        copy_term(G, G1),
   13        run(user:G1, R, Out, T0),
   14        (   R = halted(_) -> T1 = T0 ; time_reps(user:G, 1, T1) ),
   15        (   R = halted(_)
   16        ->  Reps = 1, Per = T0
   17        ;   T1 > Budget
   18        ->  Reps = 1, Per = T1
   19        ;   Reps is max(1, min(100000, floor(Budget / max(T1, 1.0e-6)))),
   20            time_reps(user:G, Reps, Per)
   21        ),
   22        write_result(ResultFile, result(R, Out, Reps, Per))
   23    ;   write_result(ResultFile, result(error(load), "", 0, 0))
   24    ),
   25    halt.
   26
   27%   halt/0,1 called by the program end the run, not the process
   28catch_halt :-
   29    catch(( redefine_system_predicate(user:halt),
   30            redefine_system_predicate(user:halt(_)),
   31            assertz((user:halt :- throw(pl2detlog_halt(0)))),
   32            assertz((user:halt(S) :- throw(pl2detlog_halt(S)))) ),
   33          _, true).
   34
   35run(G, R, Out, T) :-
   36    get_time(T0),
   37    with_output_to(string(Out),
   38                   catch(( call(G) -> R = true ; R = false ), E, err(E, R))),
   39    get_time(T2),
   40    T is T2 - T0.
   41
   42err(pl2detlog_halt(S), halted(S)) :- !.
   43err(E, error(M)) :- message_to_codes(E, M).
   44
   45message_to_codes(E, M) :-
   46    (   catch(message_to_codes_(E, M), _, fail) -> true ; format(string(M), "~q", [E]) ).
   47message_to_codes_(E, M) :- E = error(F, _), !, format(string(M), "~q", [F]).
   48message_to_codes_(E, M) :- format(string(M), "~q", [E]).
   49
   50time_reps(G, Reps, Per) :-
   51    get_time(T0),
   52    forall(between(1, Reps, _),
   53           ( catch(abolish_all_tables, _, true),
   54             with_output_to(string(_), catch(( call(G) -> true ; true ), _, true)) )),
   55    get_time(T1),
   56    Per is (T1 - T0) / Reps.
   57
   58write_result(F, T) :-
   59    setup_call_cleanup(open(F, write, S), ( writeq(S, T), write(S, '.\n') ), close(S))