SICStus Prolog: FFI slow, how to calculate Hamming weight fast?

178 Views Asked by At

When I ran the foreign code sample c1/2, as shown in the SICStus Prolog 4.3.2 manual, and compared its runtime to the corresponding Prolog code Y is X+9, I got strange timing results:

p(N, X) :- ( true1G, X is N+9, false ; X is N+9 ).

q(N, X) :- ( true1G, c1(N,X),  false ; c1(N,X)  ).

true10. true10. true10. true10. true10. true10. true10. true10. true10. true10.

true1k :- true10, true10, true10.

true1M :- true1k, true1k.

true1G :- true1M, true1k.

With the JIT enabled I observed:

| ?- call_time(p(11,X), T_p).
X = 20, T_p = 17580 ? ;                     % Prolog code
no
| ?- call_time(q(11,X), T_q).
X = 20, T_q = 66950 ? ;                     % C code
no

After turning off the JIT (SP_JIT=disabled), the timing changed like this:

| ?- call_time(p(11,X), T_p).
X = 20, T_p = 19650 ? ;                     % Prolog code
no
| ?- call_time(q(11,X), T_q).               
X = 20, T_q = 55840 ? ;                     % C code
no

Even without proper error handling and support of big integers, the C code runs almost 4x as long as the JITted Prolog code. Turning the JIT off changes the timing numbers somewhat but the big picture stays the same.

How can I speed up Hamming weight calculations in SICStus? SWI has a dedicated arithmetic function, popcount/1, but SICStus doesn't appear to support it (yet)...

0

There are 0 best solutions below