Stress CPU Threads with a Mock Compute in Python

Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Python code

26 lines
Python 3.9+
import threading
import time


def stress_cpu(iterations: int):
    result = 0
    for i in range(iterations):
        result += i * i % 1000
    return result


def run_mock_stress(thread_count: int, iterations: int):
    threads = []
    for tid in range(thread_count):
        t = threading.Thread(target=lambda: stress_cpu(iterations), name=f"worker-{tid}")
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    print(f"Completed {thread_count} threads, each doing {iterations} mock computations")


if __name__ == "__main__":
    run_mock_stress(thread_count=4, iterations=100000)

Output

stdout
Completed 4 threads, each doing 100000 mock computations

How it works

This script uses Python's threading module to spawn a configurable number of threads, each running a CPU-bound mock computation. The stress_cpu function performs a simple arithmetic loop to spike CPU usage. The threads are started in quick succession and then joined so the main program waits for all work to finish. Because of Python's Global Interpreter Lock (GIL), threads don't speed up CPU-bound Python code, but they're still useful for I/O-bound parallelism or for artificially loading a machine. The output confirms that every thread completed its full iteration count, providing a simple pass/fail check for your stress test.

Common mistakes

  • Assuming that more threads speed up CPU-bound Python work — the GIL limits true parallelism.
  • Forgotting to call `join()` on every thread, leading to unfinished work when the main program exits.
  • Starting too many threads and exhausting system resources without a limit.

Variations

  1. Use `multiprocessing.Pool` to run actual parallel CPU work across multiple cores.
  2. Pass a list of computed results to verify each thread's output, not just timing.

Real-world use cases

  • Load-testing a development server by generating artificial CPU load on the same machine.
  • Benchmarking scheduling overhead by observing how many threads the OS can switch fairly.
  • Simulating concurrent background jobs in a prototype before moving to a real task queue.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.