Skip to content

Instantly share code, notes, and snippets.

@lucaspar
Created July 14, 2023 20:17
Show Gist options
  • Save lucaspar/2cf52ab7827ae0d83d334ac4cfa0eced to your computer and use it in GitHub Desktop.
Save lucaspar/2cf52ab7827ae0d83d334ac4cfa0eced to your computer and use it in GitHub Desktop.
Progressively allocates all memory in a system
"""You probably don't want to run this.
Source: https://stackoverflow.com/a/66109163/2848528
"""
import logging
import secrets
from typing import Optional
from humanfriendly import format_size
log = logging.getLogger(__name__)
def fill_memory(
*,
num_unique_bytes_per_allocation: int = 1_024,
multiplier_per_allocation: int = 1_024**2,
max_allocations: Optional[int] = None,
) -> None:
"""Allocate available memory into a list of effectively unique bytes objects.
This function is for diagnostic purposes.
Args:
num_unique_bytes_per_allocation: Each allocation is created by
multiplying a random sequence of bytes of this length.
multiplier_per_allocation: Each allocation is created by multiplying
the random sequence of bytes by this number.
max_allocations: Optional number of max allocations.
"""
# Ref: https://stackoverflow.com/a/66109163/
num_allocation_bytes = num_unique_bytes_per_allocation * multiplier_per_allocation
log.info(
"Allocating cumulative instances of %(num_allocation_bytes)s "
"bytes (%(formatted_num_allocation_bytes)s) each. "
"Each allocation uses %(num_unique_bytes_per_allocation)s "
"unique bytes (%(formatted_num_unique_bytes_per_allocation)s) "
"with a multiplier of "
"%(multiplier_per_allocation)s (%(formatted_multiplier_per_allocation)s).",
{
"num_allocation_bytes": num_allocation_bytes,
"formatted_num_allocation_bytes": format_size(num_allocation_bytes),
"num_unique_bytes_per_allocation": num_unique_bytes_per_allocation,
"formatted_num_unique_bytes_per_allocation": format_size(
num_unique_bytes_per_allocation
),
"multiplier_per_allocation": multiplier_per_allocation,
"formatted_multiplier_per_allocation": format_size(
multiplier_per_allocation
),
},
)
# Allocate memory
allocated = []
num_allocation = 1
while True:
unique_bytes_for_allocation = secrets.token_bytes(
num_unique_bytes_per_allocation
)
allocated.append(unique_bytes_for_allocation * multiplier_per_allocation)
num_total_bytes_allocated = num_allocation * num_allocation_bytes
log.info(
"Used a total of %(num_total_bytes_allocated)s bytes"
"(%(formatted_num_total_bytes_allocated)s) "
"via %(num_allocation)s allocations.",
{
"num_total_bytes_allocated": num_total_bytes_allocated,
"formatted_num_total_bytes_allocated": format_size(
num_total_bytes_allocated
),
"num_allocation": num_allocation,
},
)
if max_allocations and (max_allocations == num_allocation):
break
num_allocation += 1
def main():
"""Entrypoint."""
logging.basicConfig(level=logging.INFO)
fill_memory()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment