473,322 Members | 1,496 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Tightening up Shootout code

I was browsing the C++ programs on "The Computer Language Shootout"
http://shootout.alioth.debian.org/ and for the heck of it, I thought
I'd try my hand at seeing if I couldn't shorten the entry for the
N-Body benchmark...
http://shootout.alioth.debian.org/de...nbody&lang=all
....Without too much concern for speed (admittedly the main emphasis of
the site), I whittled the C++ example down from 127 lines to 67 lines,
which would place it first in the lines-of-code ranking. (The Shootout
doesn't count lines consisting of only whitespace or solitary curly
braces). I'd be interested in seeing if anyone had additional ideas
for compressing it further without resorting to things like stripping
out whitespace and cramming everything onto a couple of unnaturally
long lines. Also keep in mind the constraints of the Shootout: you
only have access to the standard library, no Boost, etc. I've
included the code below, but you can see a syntax highlighted version
at ( http://sleepingsquirrel.org/cpp/body4.cpp.html ) along with an
alternative version which lays out the data structures in a different
manner ( http://sleepingsquirrel.org/cpp/body5.cpp.html ). Comments on
style would also be appreciated. (BTW, many other C++ programs on the
Shootout site look like they could use some TLC.)

Thanks,

Greg Buchholz
#include <iostream> /* The Great Computer Language Shootout */
#include <iomanip> /* http://shootout.alioth.debian.org/ */
#include <numeric> /* originally by:Christoph Bauer & David McCombs*/
#include <valarray>
#include <vector>

#define solar_mass (4 * M_PI * M_PI)
#define days_per_year 365.24
#define NBODIES 5
#define DIM 3

using namespace std;
typedef valarray<double> V;

template <class T> T mag(const valarray<T>& v){ return
sqrt((v*v).sum()); }

class Planet {
public: V pos;
V vel;
double mass;
Planet () : pos(DIM), vel(DIM) {};
Planet (double m, double x, double y, double z,
double vx, double vy, double vz) :
pos(DIM),vel(DIM)
{
mass = m; pos[0] = x; pos[1] = y; pos[2] = z;
vel[0] = vx; vel[1] = vy; vel[2] = vz;
};
};

V momentum(V& m, const Planet& p){ return m + p.mass * p.vel; }

void offset_momentum(vector<Planet>& b)
{
V z(0.0,DIM);
b[0].vel = (-1/solar_mass) * accumulate(b.begin()+1,b.end(), z,
momentum);
}

double mv_sqrd(double acc, const Planet& p)
{
return acc + p.mass * (p.vel * p.vel).sum();
}

double energy(const vector<Planet>& b)
{
double kinetic, potential = 0;

kinetic = 0.5 * accumulate(b.begin(),b.end(), 0.0, mv_sqrd);

for(int i=0; i<NBODIES; i++)
for(int j=i+1; j<NBODIES; j++)
potential += b[i].mass * b[j].mass / mag((V)(b[i].pos -
b[j].pos));

return kinetic - potential;
}

void advance(vector<Planet>& b, double dt)
{
for(int i=0; i<NBODIES; i++)
{
for(int j=i+1; j<NBODIES; j++)
{
V d = b[i].pos - b[j].pos;
double dist = mag(d);
double mag = dt / (dist * dist * dist);
b[i].vel -= b[j].mass * mag * d;
b[j].vel += b[i].mass * mag * d;
}
b[i].pos += dt * b[i].vel;
}
}

Planet dpy(Planet p)
{
p.vel *= days_per_year;
return p;
}

int main(int argc, char *argv[])
{
Planet sun(solar_mass, 0, 0, 0, 0, 0, 0);
Planet jupiter( 9.54791938424326609e-04 * solar_mass,

4.84143144246472090e+00,-1.16032004402742839e+00,-1.03622044471123109e-01,
1.66007664274403694e-03,
7.69901118419740425e-03,-6.90460016972063023e-05);
Planet saturn( 2.85885980666130812e-04 * solar_mass,
8.34336671824457987e+00,
4.12479856412430479e+00,-4.03523417114321381e-01,
-2.76742510726862411e-03, 4.99852801234917238e-03,
2.30417297573763929e-05);
Planet uranus( 4.36624404335156298e-05 * solar_mass,

1.28943695621391310e+01,-1.51111514016986312e+01,-2.23307578892655734e-01,
2.96460137564761618e-03,
2.37847173959480950e-03,-2.96589568540237556e-05);
Planet neptune( 5.15138902046611451e-05 * solar_mass,
1.53796971148509165e+01,-2.59193146099879641e+01,
1.79258772950371181e-01,
2.68067772490389322e-03,
1.62824170038242295e-03,-9.51592254519715870e-05);

Planet tmp[] = {sun, jupiter, saturn, uranus, neptune};
vector<Planet> bodies(tmp,tmp+NBODIES);
transform(bodies.begin(),bodies.end(),bodies.begin (),dpy);
offset_momentum(bodies);
cout << setprecision(9) << energy(bodies) << endl;

for(long i=atoi(argv[1]); i>0; i--) advance(bodies,0.01);

cout << energy(bodies) << endl;

return 0;
}

Jan 15 '06 #1
2 1713
Good job. I am not very surprised. The last time I looked at the
source code for some of the C++ programs on that site, I was
able to write shorter and faster C++ equivalents for at least
6 of the listed programs.

I entirely agree with you, the C++ programs need to be fixed,
firstly for performance and secondly for number of lines of code...
as you put it TLC.

Jan 16 '06 #2
vi********@gmail.com wrote:
I entirely agree with you, the C++ programs need to be fixed,
firstly for performance and secondly for number of lines of code...
as you put it TLC.


Here's another update. I got almost all of the speed back (~10%
slower) by manually unrolling the implicit inner valarray loops in
advance(), while keeping the LOC constant. Maybe a sufficiently smart
compiler could figure this out on its own. The valarrays are a
constant length of 3 after all. Oh, and it does use a somewhat ugly
looking macro...

http://sleepingsquirrel.org/cpp/body6.cpp.html

....and here's a slow (3x) but shorter version (64 non-trivial lines of
code)...

http://sleepingsquirrel.org/cpp/body7.cpp.html

Greg Buchholz

Jan 16 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Isaac Gouy | last post by:
"The Great Computer Language Shootout" has been revived on Debian: http://shootout.alioth.debian.org/index.php Only 15 of the 25 programs have PHP implementations...
0
by: Isaac Gouy | last post by:
"The Great Computer Language Shootout" was mentioned a few months ago - note that the Shootout is active and welcoming contributions at: http://shootout.alioth.debian.org/
14
by: Jacob Lee | last post by:
There are a bunch of new tests up at shootout.alioth.debian.org for which Python does not yet have code. I've taken a crack at one of them, a task to print the reverse complement of a gene...
14
by: bearophileHUGS | last post by:
The The Computer Language Shootout has just published results for Python 2.5 and Psyco 1.5.2. Comparing the old (Python 2.4) Gentoo Pentium 4 results (now not visible anymore) with the new results,...
80
by: tech | last post by:
Hi, i have the following problem In file1.h namespace A { class Bar { void foo();
31
by: Razii | last post by:
Next: fannkuch benchmark (c++) http://shootout.alioth.debian.org/gp4/benchmark.php?test=fannkuch&lang=gpp&id=2 (java) g++ -pipe -O3 -fomit-frame-pointer -finline-functions fannkuch.cpp -o...
37
by: Razii | last post by:
On Wed, 30 Apr 2008 08:00:38 -0700 (PDT), Isaac Gouy <igouy2@yahoo.comwrote: This time I am going to demonstrate a very serious problem with the shootout site. The algorithms used by C,...
31
by: Razik | last post by:
On Wed, 30 Apr 2008 08:00:38 -0700 (PDT), Isaac Gouy <igouy2@yahoo.comwrote: Let's continue. Next we deal with sum-file... ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.