mem.py

Created by andreanx

Created on May 20, 2024

1.04 KB

Tests and returns the maximum usable heap. By trying to allocate as many long strings as possible. More reliable if run directly after Python initialisation, or after running gc.collect() when available. Use : mem()


def size(o): # en 32 bits
  t = type(o)
  s = t == str and 25 + len(o) # 49 en 64 bits
  if t == int:
    s = 12 # 24 en 64 bits
    while o:
      s += 2 # 4 en 64 bits
      o >>= 15 # 30 en 64 bits
  elif t == list:
    s = 28 + 4*len(o) # 56 + 8 en 64 bits
    for so in o:
      s += size(so)
  return s

def mem(v=1):
  try:
    l=[]
    try:
      l.append(0)
      l.append(0)
      l.append("")
      l[2] += "x"
      l.append(0)
      l.append(0)
      while 1:
        try:
          l[2] += l[2][l[1]:]
        except:
          if l[1] < len(l[2]) - 1:
            l[1] = len(l[2]) - 1
          else:
            raise(Exception)
    except:
      if v:
        print("+", size(l))
      try:
        l[0] += size(l)
      except:
        pass
      try:
        l[3], l[4] = mem(v)
      except:
        pass
      return l[0] + l[3], max(l[0], l[4])
  except:
    return 0, 0

def testmem():
  m1, m2 = 0, 0
  while 1:
    t1, t2 = mem(0)
    if t1 > m1 or t2 > m2:
      m1 = max(t1, m1)
      m2 = max(t2, m2)
      input(str((m1,m2)))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.