Skip to content
Krish Ganatra
Go back

N-Body Simulation in C++: The Plan

What I’m Building and Why

Every programmer seems to have a ray tracer, a chip-8 emulator, or an N-Body simulator on their project bucket list. Guess it’s my turn to build an N-Body simulator.

An N-Body simulation is basically a physics sandbox that predicts the motion of many objects all pulling on each other with a force like gravity.

My real goal here is to finally get a proper handle on modern GPU programming and high-performance C++. An N-Body simulation is perfect because it’s easy to understand but incredibly difficult to make fast.


The O(N2)O(N^2) Problem

The most direct method is to calculate the interaction between every single pair of particles. This is called a brute-force approach.

The issue is that this is an O(N2)O(N^2) algorithm. Basically, if you double the particles, you quadruple the work. It gets slow, really fast.


The Different Approaches

There are a few ways to tackle this problem:


So, The Main Question Is…

Can a modern GPU, with its thousands of cores, run a “dumb” brute-force algorithm so fast that it beats a CPU running a “clever” algorithm like Barnes-Hut?

Probably, the answer is that it changes depending on how many particles you have, and I want to find out where that point is.


The Game Plan

Here’s how I plan to tackle this:

  1. Get It Working: First, a simple, single-threaded version in C++ that runs on the CPU. The main goal here is to make sure the physics is actually correct before trying to optimize anything.

  2. Add CPU Parallelism: Take the working code and speed it up using Intel’s TBB (Threading Building Blocks) to run across multiple CPU cores.

  3. Move to the GPU: Port the brute-force calculation to CUDA to run on the GPU. This is where I expect to see the first big performance jump.

  4. The AoS vs. SoA Showdown: Once on the GPU, I’ll test a classic optimization: Array of Structures (AoS) vs. Structure of Arrays (SoA) to see what the performance difference really is.

  5. Build Barnes-Hut: Finally, I’ll implement the Barnes-Hut algorithm on the CPU. This will be the final piece needed to compare it against the optimized GPU version and answer the main question.


Checklist

This is the checklist of questions I want answers to by the end of this project:


The Tech Stack


The Hardware

To keep the results consistent, I’ll be running all benchmarks for this project on the same hardware.


What’s Next

By the next post, I’m hoping to build out the complete CPU implementation. The goal is to get it running first with a single thread, and then create a fully parallel version to maximize its performance before we move on to the GPU implementation.

Found this useful? Drop a like!


Share this post:

Previous Post
N-Body Simulation: CPU Implementation & Performance Optimization
Next Post
Hello World!