Skip to content

Instantly share code, notes, and snippets.

@octavioranieri
Created February 14, 2024 18:07
Show Gist options
  • Save octavioranieri/db3ef02f382c787509e1da4d1b4455ee to your computer and use it in GitHub Desktop.
Save octavioranieri/db3ef02f382c787509e1da4d1b4455ee to your computer and use it in GitHub Desktop.
The code below creates artificial resource usage, useful for reproducing threshold alerts
import time
import math
import multiprocessing
from argparse import ArgumentParser
def generate_cpu_load(interval, utilization):
"Generate a utilization % for a duration of interval seconds"
start_time = time.time()
for i in range(0, int(interval)):
while time.time() - start_time < utilization / 100.0:
a = math.sqrt(64 * 64 * 64 * 64 * 64)
time.sleep(1 - utilization / 100.0)
start_time += 1
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--interval', type=int, default=60) # Default interval 60s
parser.add_argument('--cpu', type=int, default=80) # Default to 80% CPU
parser.add_argument('--memory', type=int, default=2048) # Default to 2GB
args = parser.parse_args()
buffer = bytearray(1024 * 1024 * args.memory)
processes = []
for _ in range(multiprocessing.cpu_count()):
p = multiprocessing.Process(target=generate_cpu_load, args=(args.interval, args.cpu))
p.start()
processes.append(p)
for process in processes:
process.join()
@octavioranieri
Copy link
Author

octavioranieri commented Feb 14, 2024

Usage example for running for 30 seconds, with the process consuming around 90% CPU, and 2GBs of memory:

python generate_load.py --interval 30 --cpu 90 --memory 2048

@octavioranieri
Copy link
Author

load_generator.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment