Stress CPU Threads with a Mock Compute in Python
Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.
Python code
26 linesimport 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
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
- Use `multiprocessing.Pool` to run actual parallel CPU work across multiple cores.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.