New optimization idea for N-Prolog
I’ve been experimenting with a new optimization idea for N-Prolog.
The basic idea is:
- detect predicates that are effectively functional,
- infer their input/output modes statically,
- and compile them into simpler C-style function calls.
As a first experiment, I manually wrote optimized C code using N-Prolog’s embedded C feature and compared the performance against the normal predicate execution path.
Benchmark: qsort repeated 10,000 times.
N-Prolog 5.19:
?- measure(run(qsort,10000)).
Elapsed Time=0.326355 (second) 15749722(LIPS)
SWI-Prolog:
?- time(run(qsort,10000)).
% 6,160,005 inferences, 0.358 CPU in 0.358 seconds
% (100% CPU, 17189389 Lips)
The optimized version became roughly 3–4x faster than the ordinary predicate-oriented execution path.
The motivation is that many Prolog programs contain predicates that are logically relational, but operationally behave almost like functions. qsort is a typical example.
If such predicates can be detected automatically through mode inference and static analysis, they may be compiled into much simpler execution paths while still preserving ordinary Prolog semantics for general predicates.
I’m currently working on the design of the mode inference engine itself.
Notes and experimental code are in mode.pl if anyone is interested.
I’d also be interested to hear whether similar ideas were explored historically in Prolog systems beyond the usual Mercury-style mode systems.