"""
01_free_lists.py -- implicit vs explicit vs segregated free lists
==================================================================

[Questions this demo answers]
  - The implicit list walks EVERY block on each malloc. How much does threading
    the free blocks into their own list (explicit) cut the search?
  - And splitting the free list by size class (segregated) -- how much further?
  - Why do real allocators use segregated lists?

[How to run]
  python3 01_free_lists.py

[How to read the output]
  The same seeded workload runs on each allocator; the table reports the
  average number of blocks examined per malloc (the throughput proxy) and the
  peak utilization. Lower search cost at equal utilization is the win.

[About this tool]  heap.py / freelists.py are teaching models (Python); not
  the malloclab C deliverable.

[Systems link / CS:APP 9.9.13-9.9.14]
  Explicit free lists make malloc's cost proportional to the number of FREE
  blocks, not all blocks. Segregated lists make it proportional to the free
  blocks IN ONE SIZE CLASS -- effectively constant -- which is why production
  allocators use them.
"""

import heap
import freelists


def run(cls, label, size=8192, rounds=1500, seed=15213, **kw):
    import random
    h = cls(size, **kw) if kw else cls(size)
    rng = random.Random(seed)
    live, peak, nmalloc = [], 0.0, 0
    for _ in range(rounds):
        if live and rng.random() < 0.42:
            h.free(live.pop(rng.randrange(len(live))))
        else:
            p = h.malloc(rng.choice([16, 24, 48, 64, 120, 200, 400]))
            if p is not None:
                live.append(p)
            nmalloc += 1
        peak = max(peak, h.utilization())
    return label, h.search_steps / nmalloc, peak


def main():
    print("=== Demo 01: free-list organizations ===\n")
    print("  Same seeded workload on an 8 KiB heap; 'steps/malloc' = blocks examined.\n")
    rows = [
        run(heap.Heap, "implicit (first fit)"),
        run(heap.Heap, "implicit (best fit)", fit="best"),
        run(freelists.ExplicitHeap, "explicit free list"),
        run(freelists.SegHeap, "segregated (8 classes)"),
    ]
    print("  %-26s %-16s %s" % ("allocator", "steps / malloc", "peak utilization"))
    base = None
    for label, steps, peak in rows:
        if base is None:
            base = steps
        print("  %-26s %-16.1f %.2f" % (label, steps, peak))
    impl = rows[0][1]
    seg = rows[-1][1]
    print("\n  The implicit list scans allocated blocks too, so it examines the most.")
    print("  The explicit list scans only free blocks; the segregated list scans only")
    print("  free blocks in the right size class -- about %.0fx fewer than implicit" % (impl / seg))
    print("  here -- at the same utilization. That is why real allocators are")
    print("  segregated-fit.\n")
    print("Observations:")
    print("  * Implicit list: simple, but malloc is O(total blocks).")
    print("  * Explicit list: malloc is O(free blocks); the prev/next links live inside")
    print("    the free blocks' unused payload, so they cost no extra memory.")
    print("  * Segregated list: malloc is ~O(free blocks in one size class) -- nearly")
    print("    constant -- which is the design production allocators use.")


if __name__ == "__main__":
    main()
