A high-performance 2D particle simulation using multithreading in Python. Simulates particle motion and collisions in a bounded space with real-time grid-based spatial partitioning for efficient collision detection.
- Simulates 10,000 particles (customizable)
- Multithreaded for better CPU utilization (default: 8 threads)
- Realistic collision handling with elastic response
- Spatial grid for optimized neighbor checks
- Per-step logs of:
- Duration
- Collisions resolved
- CPU utilization
- Grid rebuild time
- Active threads
- Built-in performance metrics: FPS, total simulation time, CPU average
-
Initialization:
- Each particle is randomly assigned position, velocity, radius, and mass.
- The 2D space is divided into grid cells based on particle size.
-
Each Simulation Step Includes:
- Particle movement update
- Boundary collision management
- Grid repopulation
- Particle-particle collision resolution across cells (with lock-based safety)
- Performance logging (timing, CPU, etc.)
-
Multithreading:
- Uses
ThreadPoolExecutorfor parallel updates and collision checks. - Dynamically distributes work across threads.
- Uses
| File | Description |
|---|---|
physics_simulator.py |
Main simulation script |
output.txt (optional) |
Console logs of each simulation step |
- Python 3.7+
- psutil: for measuring CPU usage
Install required package:
pip install psutilpython physics_simulator.pyYou’ll see logs printed step-by-step in the console, e.g.:
Step 1/50 | Duration: 0.048s | Collisions: 2400 | CPU util: 99.7% | Active threads: 9 | Grid Rebuild: 0.005s
...
At the end, summary metrics like total time, FPS, and total collisions will be shown.
You can tweak simulation parameters at the top of physics_simulator.py:
no_of_particles = 10000 # total particles
no_of_sim_steps = 50 # how many steps to simulate
no_of_threads = 8 # parallel threads to use
width = 1000 # width of the space
height = 800 # height of the space
particle_max_initial_velocity = 100- Total simulation time
- Average, max, min step duration
- Estimated FPS
- Total collisions handled
- Average CPU usage per step
- Try changing
no_of_particlesorno_of_threadsto see how it scales. - You can redirect output to a file:
python physics_simulator.py > output.txt- Particle locking ensures safe concurrent updates.
- CPU utilization may show >100% due to multithreading on multi-core CPUs (normal in Python’s
psutil). - Grid-based collision detection significantly boosts performance compared to brute-force.
- Add visualization (e.g., using
pygameormatplotlib) - Profile memory usage
- Try multiprocessing for CPU-bound steps
- Experiment with alternative data structures (QuadTrees, etc.)
T Jaiwanth
Happy Simulating! 🚀