D code optimization

Sandu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 22 09:09:49 PDT 2016


It is often being claimed that D is at least as fast as C++.
Now, I am fairly new to D. But, here is an example where I want 
to see how can this be made possible.

So far my C++ code compiles in ~850 ms.
While my D code runs in about 2.1 seconds.

The code translated in D looks as follows (can't see any attach 
button here):

import std.stdio, std.math;
import std.datetime;


int main() {

	StopWatch sw;
         sw.start();

	double C=0.0;

	for (int k=0;k<10000;++k) { // iterate 1000x

		double S0 = 100.0;
		double r = 0.03;
		double alpha = 0.07;
		double sigma = 0.2;
		double T = 1.0;
		double strike = 100.0;
		double S = 0.0;


		const int n = 252;

		double dt = T / n;
		double R = exp(r*dt);

		double u = exp(alpha*dt + sigma*sqrt(dt));
		double d = exp(alpha*dt - sigma*sqrt(dt));

		double qU = (R - d) / (R*(u - d));
		double qD = (1 - R*qU) / R;


		//double* call = new double [n + 1];
		double[] call = new double[n+1];

		for (int i = 0; i <= n; ++i)  call[i] = fmax(S0*pow(u, 
n-i)*pow(d, i)-strike, 0.0);
		
		for (int i = n-1; i >= 0 ; --i) {
			for (int j = 0; j <= i; ++j) {
				call[j] = qU * call[j] + qD * call[j+1];
			}
		}

	 	C = call[0];

	    //delete call; // since D is has a garbage collector, 
explicit deallocation of arrays is not necessary.
	    // nevertheless we do this
	}

     long exec_ms = sw.peek().msecs;

     writeln("Option value: ",  C, " / execution time: ", exec_ms, 
" ms\n" );

	return 0;
}


More information about the Digitalmars-d-learn mailing list