Keeping tight allocation-free loops interruptible

Viewed 45

I want to keep an otherwise alloc-free loop interruptible.

To do this, I'm adding a dummy allocation to the loop.

My question is about minimizing the allocation costs.

Here is a minimal version of what I am doing:

let my_dummy_alloc () =
  ignore (Sys.opaque_identity (ref 0));;
let my_fun x =
  my_dummy_alloc ();
  x;;

let my_handler _ = raise Exit;;
Sys.(set_signal sigint
       (Signal_handle my_handler));

for i = 1 to int_of_string Sys.argv.(1) do
  ignore (Sys.opaque_identity (my_fun i));
done;;

ocamlopt emits AMD64 asm code that looks like this:

_camlTt__my_fun_166:
        subq    $8, %rsp
L104:
        subq    $16, %r15       # I want 8
        cmpq    8(%r14), %r15
        jb      L105
L107:
        leaq    8(%r15), %rbx
        movq    $1024, -8(%rbx)
        movq    $1, (%rbx)      # unneeded
        addq    $8, %rsp
        ret
L105:
        call    _caml_call_gc
L106:
        jmp     L107

From what I understand about the internal representation of heap allocated blocks, blocks comprising one header word and zero data words should be possible.

How can I can generate such blocks using OCaml code?


Edit. I had a hunch ...

... that Obj.new_block might help. It did not. Instead, the runtime quadrupled and the interruptability was gone.

Looking at the asm code, I noticed call _caml_c_call, which explains the effects I observed. Back to square one!

0 Answers
Related