Speed Tests

I'm currently doing an optimization run on JBox2d, I decided to run a couple of speed tests with the Box2d versions I'm most comfortable with, Java and C++, to get an idea of relative performance and measure how effective my optimizations are. I coded the same test in Java and C++, which would look like this if graphics were displayed, which they are not (to get a better sense of the pure library performance):

Image

The piston just keeps pumping, so things never settle down. Each test runs for 1000 physics frames. This is a decent test of the contact handling, but not of joints; I'll probably make another benchmark using those later, but for now I'm seeing most of the bottlenecks in the contacts, so...

Here are the details if you're curious to run the tests yourself:

Java file: http://www.jbox2d.org/jbox2d-2.0.1-speedTest.jar
Instructions: Download the .jar, and browse to the directory in the command prompt/shell (don't double click the .jar, because though it is executable, you likely won't see the console output or be able to specify JVM flags), and run it with the command "java -jar -server -Xms128M -Xmx256M jbox2d-2.0.1-speedTest.jar 40" (without the quotes). If you change the flags to -Xms1024M and -Xmx2048M you'll probably get slightly higher performance, but allowing a 2 gigabyte heap is just ridiculous, even for Java...

C++: Download the attached SpeedTest.cpp file, and do whatever magic it is on your system that adds a C++ file to the Box2d project (which you must have, also), then run it! Sorry, I'd provide executables, but I'm on a Mac, and I don't think a Mac binary would help too many people.

I'm curious to see what other people get - it would be useful to know your system details, including what JVM you're running.

My results (OS X 10.5.3, Intel 2.4 gHz w/2 gig RAM, Apple's Java 1.6):

Java average FPS: 568.03015
C++ average FPS: 708.61

...which shocks me a little bit, I expected a much larger difference between Java and C++ (and saw one before I optimized, which means my work paid off - on this test, with a couple hours work I was able to bump up performance by a full 100 fps). The caveat being, of course, that it takes a LOT of work to squeeze the performance out of Java, and I think this is about as good as can be done, whereas the C++ version hasn't needed much tweaking because it's fast enough already. Also, note that with a 1.5 JVM, I only get ~450 fps for the Java version. You lose another ~100 fps by not using the -server flag, too. I haven't checked this on Windows or using Sun's JVM, which is pretty important since that's what most people use...

I did not do an Actionscript version of this because I have no idea how to run AS3 code without the whole graphics thing being active, and it seemed unfair to do the Java and C++ ones as console programs and then compare that to an AS3 one with the graphics output slowing things down. Maybe an AS3 expert has an idea how to get a good sense about to decouple the library timing from the graphics?
There is a lot that can be done to speed up the C++ version. The main thing is to make the solver more cache friendly. Also, Dirk Gregorious recently discovered that the position solver works quite well with just one iteration.
Erin Catto wrote:
There is a lot that can be done to speed up the C++ version. The main thing is to make the solver more cache friendly.

What's the main thing that needs to be done to achieve that? It's mainly a matter of replacing random array accesses with sequential ones, right? I would think that's difficult to do, especially with an island solver.

It's worth noting re: relative performance that this is an excellent example of the type of optimization that will unfortunately not benefit the Java port very much - Java's virtual machine attempts to optimize for cache hits automatically, and furthermore guarantees nothing about the memory layout of objects, so it's very difficult to predict what code changes will reduce misses (though - irritatingly enough - minor and seemingly meaningless code changes and reordering often do affect this behavior quite dramatically, but depend strongly on VM version and architecture). Even if you create a simple array of bodies, after one garbage collection the objects themselves may very well be scattered all over the heap (though the references to these objects will likely still be contiguous).

So anyone using the Java port, be aware that barring JVM changes, we're really pushing the edge of what we can achieve here, and many of the gains the C++ version sees from this point on will not be reflected in Java. When everything settles and is fully optimized in both versions, I'd expect Java to be running at approximately half the speed of the C++ one.
We should create a temporary array of the velocities and not allow the constraint solver to touch the bodies during iteration. Mass properties should be temporarily cached in the constraint.

WRT the contact solver, we should have just two arrays of data:
1 - a single array of island contact constraint structures, accessed sequentially
2 - a single array containing the island body velocities (linear + angular in same array).

With this, we can easily double the performance of the C++ contact solver.
Quote:
...I'm curious to see what other people get ...

On Intel Core 2 CPU @1.83 GHz, 2GB RAM, WINXP

For MS Visual C++ 2005, std:: deleted but <time.h> included, dont treat warn as error
average FPS: 569.54 (168.10 bullets on)

For Java 1.6.0_03 (w/o -server flag)
average FPS: 406.64716
I'd be quite interested in how the C# version performs; if it's similar to the Java version, then it looks like our simulator is 20x slower than box2D! 🙁

Also, do you know how many contacts are solver per frame in your test?
In that test there are 206 bodies and between 200 and 600 contacts, at least after the first 200 frames (during which the shapes are still piling up). You can run the example in the testbed to see for yourself by calling the following function and passing m_world:
Code:
void CreatePistonWorld(b2World* world)
{
   
   // Define crank.
   b2PolygonDef sd;
   sd.SetAsBox(0.5f, 2.0f);
   sd.density = 1.0f;
   
   b2RevoluteJointDef rjd;
   
   b2Body* prevBody = world->GetGroundBody();
   
   b2BodyDef bd;
   bd.position.Set(0.0f, 7.0f);
   b2Body* body = world->CreateBody(&bd);
   body->CreateShape(&sd);
   body->SetMassFromShapes();
   
   rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f));
   rjd.motorSpeed = 1.0f * b2_pi;
   rjd.maxMotorTorque = 1000000.0f;
   rjd.enableMotor = true;
   b2RevoluteJoint* m_joint1 = (b2RevoluteJoint*)world->CreateJoint(&rjd);
   
   prevBody = body;
   
   // Define follower.
   sd.SetAsBox(0.5f, 4.0f);
   bd.position.Set(0.0f, 13.0f);
   body = world->CreateBody(&bd);
   body->CreateShape(&sd);
   body->SetMassFromShapes();

   rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f));
   rjd.enableMotor = false;
   world->CreateJoint(&rjd);

   prevBody = body;
   
   // Define piston
   sd.SetAsBox(5.0f, 1.5f);
   bd.position.Set(0.0f, 17.0f);
   body = world->CreateBody(&bd);
   body->CreateShape(&sd);
   body->SetMassFromShapes();
   
   rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f));
   world->CreateJoint(&rjd);
   
   b2PrismaticJointDef pjd;
   pjd.Initialize(world->GetGroundBody(), body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f));
   
   pjd.enableMotor = false;
   
   b2PrismaticJoint* m_joint2 = (b2PrismaticJoint*)world->CreateJoint(&pjd);
   
   // Create payloads
   for (int i=0; i<100; ++i)
   {
      sd.SetAsBox(0.4f,0.3f);
      sd.density = 2.0f;
      bd.position.Set(-1.0f, 23.0f + i);
      bd.isBullet = false;
      body = world->CreateBody(&bd);
      body->CreateShape(&sd);
      body->SetMassFromShapes();
   }
   
   b2CircleDef cd;
   cd.density = 2.0f;
   cd.radius = 0.36f;
   for (int i=0; i<100; ++i)
   {
      bd.position.Set(1.0f, 23.0f + i);
      bd.isBullet = false;
      body = world->CreateBody(&bd);
      body->CreateShape(&cd);
      body->SetMassFromShapes();
   }
   
   sd.density = 0.0f;
   sd.friction = 0.0f;
   sd.SetAsBox(1.0f, 100.0f);
   b2BodyDef bd2;
   bd2.position.Set(-6.1f,50.0f);
   b2Body* bod = world->CreateBody(&bd2);
   bod->CreateShape(&sd);
   bd2.position.Set(6.1f,50.0f);
   bod = world->CreateBody(&bd2);
   bod->CreateShape(&sd);
}


Keep in mind, raigan, that the 500/700 fps stats are for physics only, so don't compare actual in-game frame rates to these stats - the Java testbed version of this test struggles to run at 60 fps because of the rendering overhead (software rendering), and in fact, most examples that I've run are overwhelmingly dominated by graphics overhead, not physics.

Also, one thing that's bugging me a little is that the frame rates my test reports for a whole run differ substantially from the frame rates that the testbed reports per frame. Some of this could be due to the difference in trying to measure a few ms versus several seconds, I'm not sure. Here's the code I'm using:

Code:
   std::clock_t start;
   std::clock_t end;
   start = std::clock();

   for (int32 i = 0; i < nFrames; ++i)
   {
      world.Step(timeStep, iterations);
   }
   
   end = std::clock();
   
   double seconds = ( double ( end ) - start ) / CLOCKS_PER_SEC;
   double fps = nFrames / seconds;
   return fps;


Anyone see any problem with that?
Thanks! I haven't been able to compile box2D since v1, but you've just reminded me that I should try it again now that I've got VS2005.

Is 200-600 the number of contact points, or contact structs? (Each struct could represent 2 contact points..)

Sadly I _am_ only considering the time spent simulating -- 100 boxes (~150 contacts per frame) runs at 40ms/frame in our simulator. This is probably due to how we're handling collision, which is a bit, uh, "novel" 🙁

I figured computers these days were crazy fast -- if Half-Life 2 can run several ragdolls and rigid bodies along with pumping out however many triangles per second, surely we can simulate a couple hundred boxes in 2D! Apparently not though..
raigan wrote:
Is 200-600 the number of contact points, or contact structs? (Each struct could represent 2 contact points..)

That's the number of contact points.
Quote:
Sadly I _am_ only considering the time spent simulating -- 100 boxes (~150 contacts per frame) runs at 40ms/frame in our simulator. This is probably due to how we're handling collision, which is a bit, uh, "novel" 🙁

Ah, ok - out of curiosity, what are the main differences between your method and Box2d's? Are you doing CCD for everything, or is it something else? Any reason in particular you can't move to a similar method?
ewjordan wrote:
raigan wrote:
Ah, ok - out of curiosity, what are the main differences between your method and Box2d's? Are you doing CCD for everything, or is it something else? Any reason in particular you can't move to a similar method?


We're using a position-based solver, and for collision doing something similar to "Modeling concave constraints" (Trinkle).. basically, generating constraints speculatively (for things that MIGHT collide) and then during constraint iteration performing some simple tests to decide which constraints to actually solve. Right now with 100 boxes we're generating ~1500 constraints, ~150 of which are solved per iteration. We're looking into ways to cut this down, since it's one of the major bottlenecks.

Essentially we're doing limited collision detection per-iteration, which is unavoidable with position-based solvers. One of the fundamental problems with position-based solvers is that stuff moves per iteration, which means that all the constraint parameters (Jacobians, contact points, etc.) have to be recalculated per-iteration. This makes solving a bit slower, but the up side is that relatively few iterations are needed (i.e 4 iterations is often enough). And friction is enough of a problem that we're adding velocity-level solving.. position-based friction is simple for planar shapes, but really, really horrible for round shapes like circles or capsules.

An additional problem for us is that we're trying to avoid penetration (we have a rope simulation based on sweep tests which totally fails on penetration), so we _need_ to generate collisions before they actually occur, rather than using a penetration-based method. Although, Box2D might be fine for this now that there's CCD and a core shape -- basically as long as the core shapes NEVER penetrate each other, we'd be fine.

The benefit of our method is that it prevents flythrough without having to resort to more complex algos (i.e CCD and SAP, neither of which I understand well enough to implement efficiently..); we're just using simple distance queries, AABBs, and a grid. It's also trivial to support concave-vs-concave collision (in our sim, a box is unoptimized -- it's just a mesh with 4 convex verts and 4 edges). Another plus is that you don't need to mess with PD controllers to get stable motorized animation. There are other benefits which we've had to cut due to time constraints -- mainly, that you're not limited to rigid physics, and can handle "skinned" collision geometry.

The biggest reason we're sticking with our simulation, despite the awesomeness of Box2D, is that we understand it 😉
Seriously, this is a huge difference -- we've tried figuring out how to calculate Jacobians for impulse-based methods, but it never works; we actually haven't had success in hand-deriving constraint for our solver, BUT we found a working solution -- write out the constraint in terms of body states, send it through LiveMath!, and it spits out the partial derivatives we need. This way, we can very easily derive constraint equations for arbitrary constraints, and this is necessary for a lot of the things we're doing (character controllers).

We're still agonizing over whether we should continue development or just switch over to Box2D though.. it's an order of magnitude faster! I'm just superstitious about impulse-based solvers, I've never had good experiences, and our position-based method is always stable without needing to tweak lots of stuff.

Original thread: https://box2d.org/forum/viewtopic.php?t=979