Detecting if memory is low under ocaml
I need a way to detect if memory is low, so that my ocaml program could react on this. Could you point me how to implement or use it?
Any hints?
Bye开发者_如何学编程 Andreas
If you are only allocating inside the heap (you would know if you were allocating outside the heap), use (Gc.quick_stat()).Gc.heap_words
to get the size of the heap, a good approximation for the entire memory used by OCaml. As its name indicates, this field is expressed in either 32- or 64-bit words.
You must compare this to some limit that OCaml cannot guess for you, which is the maximum memory you want your program to use. The value depends how much memory you want to leave to other processes, whether you consider swapping acceptable, and so on. This second value depends on your system, not on OCaml. Even if you want to compute this value as a fixed fraction of the total quantity of RAM on your computer, I do not know any portable way to do this with OCaml: you have to tell us more about your system.
Do not try to use free_words
and similar fields in the GC stats. These only tell you how the space is divided inside the heap. "Free" words still take up room, and it is the Garbage Collector's role to keep this value at a reasonable fraction of the total. It resizes the heap in order to do this.
精彩评论