Nguyen Kim Son

Archive for the ‘Project Euler’ Category

Performance test between generics and collection of Objects

In Project Euler on May 14, 2012 at 12:47 pm

Below is the code in C# for testing the performance of 2 approaches in creating a collection: one by using Object, then implicit casting and the other using generics technique.
In the code, we first fill up 2 stacks, one created by collection of objects, the second created using generics. Both contain lot of elements (5E7). We then calculate the sum of all elements. The first one takes 6.3 secs, while the second one takes 1.3 sec. The reason of more than 5 times difference in execution time is due to the overhead of casting.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DiverseTests
{
class Program
{
private const double M = 5e7;
public static Stack GetStackB4Generics()
{
Stack s = new Stack();
for (int i = 0; i < M; i++)
{
s.Push(i);
}
return s;
}

public static Stack GetStackAfterGenerics()
{
Stack s = new Stack();
for (int i = 0 ; i < M ; i++)
{
s.Push(i);
}
return s;
}

static void Main(string[] args)
{
DateTime now = DateTime.Now;
Stack s1 = GetStackB4Generics();
double sum1 = 0;
while (s1.Count != 0)
{
sum1 += (int)s1.Pop(); //cast
}
Console.WriteLine("Sum of stack 1 is " + sum1);
Console.WriteLine(DateTime.Now.Subtract(now));
now = DateTime.Now;

Stack s2 = GetStackAfterGenerics();
double sum2 = 0;
while (s2.Count != 0)
{
sum2 += s2.Pop(); //no cast
}
Console.WriteLine("Sum of stack 2 is " + sum2);
Console.WriteLine(DateTime.Now.Subtract(now));

}
}
}

Advertisements

What is Project Euler and why should we participate in?

In Project Euler on August 15, 2010 at 8:54 am

Leonhard Euler

Project Euler is a website that proposes a series of mathematical problems but usually need to be solved by a computer scientist. Some are quite easy and can be done by “brute force”, i.e. scanning all the possibilities without any “sieve”.
So why should we participate in? There are two main reasons for anyone, not necessarily in the domain of computer science or mathematics to attack some:

  • To see mathematical problems in a different way, maybe less beautiful than the pure one, but surely more practical.
  • To understand¬† how¬† a program works in a machine, be conscious of each Byte used in memory, etc.

Project Euler has been for me an interesting adventure: it has helped me to get out of FM(Football Manager) world when it seems hopeless and gave me a different point of view towards modern mathematicians.
My next posts will be concentrate on problems on Project Euler, their traps and their solutions.