It seems like DMD doesn't optimize tail recursion very well

James Pelcis jpelcis at gmail.com
Fri Jun 9 08:03:45 PDT 2006


You seem to be right.  Just to make a fairer test, I made both versions 
use the same timing code and did a DMC vs. DMD.  I'm not the best of 
coders though, so it might not be perfect.

------------------------------------------
C++:
------------------------------------------
#include <iostream.h>

int Ack(int a, int b)
{
     if (a == 0)
         return b + 1;
     else if (b == 0)
         return Ack(a - 1, 1);
     else
         return Ack(a - 1, Ack(a, b - 1));
}

long long getCount()
{
     asm
     {
         rdtsc;
         ret;
     }
}

int main()
{
     long long start = getCount();
     Ack(3, 11);
     long long stop = getCount();
     cout << stop-start << " clock cycles elapsed.\n";

     return 0;
}

------------------------------------------
D:
------------------------------------------
private import std.stdio;

int Ack(int a, int b)
{
     if (a == 0)
         return b + 1;
     else if (b == 0)
         return Ack(a - 1, 1);
     else
         return Ack(a - 1, Ack(a, b - 1));
}

long getCount()
{
	asm
	{
		rdtsc;
		ret;
	}
}

void main()
{
     long start = getCount();
     Ack(3, 11);
     long stop = getCount();
     writefln("%d clock cycles elapsed.", stop - start);
}

------------------------------------------

My results (averaged and rounded) were 5,575,010,530 for C++ and 
8,339,840,041 for D.  Since it was with the same linker, optimizer, 
etc., this is a bad sign.  Is the problem in the code or the compiler?



More information about the Digitalmars-d mailing list