Why is this D code slower than C++?

Bill Baxter dnewsgroup at billbaxter.com
Tue Jan 16 23:23:46 PST 2007


Bradley Smith wrote:
> Jacco Bikker wrote several raytracing articles on DevMaster.net. I took 
> his third article and ported it to D. I was surprised to find that the D 
> code is approx. 4 times slower than C++.
> 
> The raytracer_d renders in approx. 21 sec and the raytracer_cpp renders 
> in approx. 5 sec. I am using the DMD and DMC compilers on Windows.
> 
> How can the D code be made to run faster?
> 
> Thanks,
>   Bradley
> 

That is pretty weird.

I noticed that it doesn't work properly with -release add to the 
compiler flags.  If I do add it I just get a lot of flashing of my 
desktop icons when I run it, rather than a window popping up with a 
raytracer inside.  Any idea why?

Anyway, after some tweaking of the D version I got it down to 15 sec, vs 
10 sec for C++ version on my machine.

Mainly the kinds of thing I did were to make more things inout 
parameters so they don't get passed by value.  Also it looks like maybe 
your template math functions like DOT and LENGTH aren't getting inlined. 
   Replacing those with the inline code in hotspots like the sphere 
intersect function sped things up.

Here's was the version of Sphere.Intersect I ended up with:

   int Intersect( inout Ray a_Ray, inout float a_Dist ) {
     vector3 v = a_Ray.origin;
     v -= m_Centre;
     //float b = -DOT!(float, vector3) ( v, a_Ray.direction );
     vector3 dir = a_Ray.direction;
     float b = -(v.x * dir.x +
                 v.y * dir.y +
                 v.z * dir.z);
     float det = (b * b) - (v.x*v.x+v.y*v.y+v.z*v.z) + m_SqRadius;
     int retval = MISS;

     if (det > 0) {
       det = sqrt( det );
       float i2 = b + det;
       if (i2 > 0) {
         float i1 = b - det;
         if (i1 < 0) {
           if (i2 < a_Dist) {
             a_Dist = i2;
             return INPRIM;
           }
         } else {
           if (i1 < a_Dist) {
             a_Dist = i1;
             return HIT;
           }
         }
       }
     }
     return retval;
   }

The inout on the Ray parameter and the other changes to this function 
alone change my D runtime from 22 sec to 15 sec.

I also tried making similar changes to the C++ version, but they didn't 
seem to affect the runtime at all.

--bb


More information about the Digitalmars-d-learn mailing list