Finding large difference b/w execution time of c++ and D codes for same problem

Sparsh Mittal sparsh0mittal at gmail.com
Tue Feb 12 12:35:40 PST 2013


I am writing Julia sets program in C++ and D; exactly same way as 
much as possible. On executing I find large difference in their 
execution time. Can you comment what wrong am I doing or is it 
expected?


//===============C++ code, compiled with -O3 ==============
#include <sys/time.h>
#include <iostream>
using namespace std;
const  int DIM= 4194304;

struct complexClass {
   float r;
   float i;
   complexClass( float a, float b )
   {
     r = a;
     i = b;
   }


   float squarePlusMag(complexClass another)
   {
     float r1 = r*r - i*i + another.r;
     float i1 = 2.0*i*r + another.i;

     r = r1;
     i = i1;

     return (r1*r1+ i1*i1);
   }
};


int juliaFunction( int x, int y )
{

   complexClass a (x,y);

    complexClass c(-0.8, 0.156);

   int i = 0;

   for (i=0; i<200; i++) {
    if( a.squarePlusMag(c) > 1000)
       return 0;
   }

   return 1;
}


void kernel(  ){
   for (int x=0; x<DIM; x++) {
     for (int y=0; y<DIM; y++) {
       int offset = x + y * DIM;
       int juliaValue = juliaFunction( x, y );
	//juliaValue will be used by some function.
     }
   }
}


int main()
{

   struct timeval start, end;
   gettimeofday(&start, NULL);
   kernel();
   gettimeofday(&end, NULL);
   float delta = ((end.tv_sec  - start.tv_sec) * 1000000u +
          end.tv_usec - start.tv_usec) / 1.e6;


   cout<<" C++ code with dimension " << DIM <<" Total time: "<< 
delta << "[sec]\n";
}






//=====================D++ code, compiled with -O -release 
-inline=========

#!/usr/bin/env rdmd
import std.stdio;
import std.datetime;
immutable int DIM= 4194304;


struct complexClass {
   float r;
   float i;

   float squarePlusMag(complexClass another)
   {
     float r1 = r*r - i*i + another.r;
     float i1 = 2.0*i*r + another.i;

     r = r1;
     i = i1;

     return (r1*r1+ i1*i1);
   }
};


int juliaFunction( int x, int y )
{

   complexClass c = complexClass(0.8, 0.156);
   complexClass a= complexClass(x, y);


   for (int i=0; i<200; i++) {

     if( a.squarePlusMag(c) > 1000)
       return 0;
   }
   return 1;
}


void kernel(  ){
   for (int x=0; x<DIM; x++) {
     for (int y=0; y<DIM; y++) {
       int offset = x + y * DIM;
       int juliaValue = juliaFunction( x, y );
       //juliaValue will be used by some function.	
     }
   }
}


void main()
{
   StopWatch sw;
   sw.start();
   kernel();
   sw.stop();
   writeln(" D code serial with dimension ", DIM ," Total time: ", 
(sw.peek().msecs/1000), "[sec]");
}

//================
I will appreciate any help.


More information about the Digitalmars-d-learn mailing list