MEMORY
Know how much free memory for an application
There is a toolbox call, MaxBlock, which returns a long integer which is the size of the largets block of memory available after heap compaction were to be performed. Called as:
temp& = fn maxblock
You could do this to get the amount of free bytes available:
FreeBytes&=MEM(_maxAvail)
The problem with this, I think, is that even though there is that much available you may not be able to alocate it as one block. The FNs below will do what you want. FN binarySearach& will find the maximum amount of memory that can be alocated as one continous block, to within less than1 KB. And, because it uses a binary search, it is fast. Call it like this:
FreeBytes&=FN binarySearach& 'how much memory do we have to work with
You can then alocate a handle of that size. (I usually alocate a little less, like 90%, to leave some free memory for the program to use.)
'--------------------------Binary search Functions ---------------------------
'The next 3 functions finds the amount of free memory
'----------
'this fn uses recursion to
'adds smaller and smaller chuncks of memory to the handle
'to find the largest amount of free memory to within 1 KB
LOCAL FN searchDown&(num&,searchsize&)
searchsize&=searchsize&>>1 'divide by two (shift bits right)
LONG IF searchsize&>1024 'leave some bytes free
numOK&=num&+searchsize& 'adds the next chunck
hand& = FN NEWHANDLE (numOK&) '_(numOK&)'can we make a handle?
isHandZero=hand&>0 '0 means it did not work
whatError=SYSERROR 'zero if no error
DEF DISPOSEH(hand&) 'get rid of handle
LONG IF isHandZero=0 OR whatError<>_Noerr
num&=FN searchDown&(num&,searchsize&) 'didn't work, try adding the next smallest number to the original number
XELSE
num&=FN searchDown&(numOK&,searchsize&) 'did work, try adding the next smallest number to the new number
END IF
END IF
END FN=num& 'return the largrest number that we could make a handle with
'----------
'this fn keeps doubling handel size until error
LOCAL FN searchUp&
numOK&=1024 'start with 1 KB
err=_False 'no error so far
DO
hand& = FN NEWHANDLE (numOK&) '_clear (numOK&)
whatError=SYSERROR
LONG IF hand&=0 OR whatError<>_Noerr
err=_True 'exit loop
XELSE
numOK&=numOK&<<1 'no error then multiply by 2 (bit shift)
END IF
DEF DISPOSEH(hand&) 'close handle
UNTIL err
numOK&=numOK&>>1 'go back to the last one that was good
END FN=numOK& 'return largest handle that was created
'----------
'this fn finds the amount of free memory
LOCAL FN binarySearach&
numOK&=FN searchUp& 'keep doubling handel size until error
freeByts&=FN searchDown&(numOK&,numOK&) 'adds smaller and smaller chuncks of memory to the handle
END FN=freeByts&
'----------
|