Parallell computing in .net 4

by Christer 29. November 2009 18:12

There are some new neat feature for doing parallel computing and taking advantage of multiple cores in .net 4, and i thought id check some of them out.

First i need a testsetup, and i thought id just use something that use up a lot of cpu and cooked together a simple console app that counts the number of primes in a specified range.

static void Main(string[] args)
{
    Console.WriteLine("Starting..");
    DateTime d = DateTime.Now;

    var c = Enumerable.Range(1, 100000)
        .Where(i => IsPrime(i))
        .Count();

    TimeSpan elapsed = DateTime.Now - d;

    Console.WriteLine(string.Format("Done!. Found {0} primes in {1} ms\n\nPress enter to exit",c, elapsed.TotalMilliseconds));

    Console.ReadLine();
}

and the IsPrime function:

static bool IsPrime(int val)
{
    for (int i = 2; i <= val / 2; i++)
        if (val % i == 0)
            return false;

    return true;
}

The primecheck isnt built for speed, its built for hogging up cpu and giving me a result that i can verify that its correct (Though some might complain that it will treat 1 as a prime, but hey! Im not a mathematician, 1 is a perfectly good prime in my world =)

The initial testrun gives:

Starting..
Done!. Found 9593 primes in 1201,0687 ms 

Press enter to exit

After a bunch of more runs it seems to keep around 1150ms to 1250ms, so about 1200 ms seems about right.

good, we have our baseline, but thats not very interesting so how do we get this to run in parallell? Well, it isnt very hard. All thats needed is to add .AsParallel() to the initial loop like this:

var c = Enumerable.Range(1, 100000)
    .AsParallel()
    .Where(i => IsPrime(i))
    .Count();

Ok, that was easy enough. but does it do anything? First run gave:

Starting..
Done!. Found 9593 primes in 697,0399 ms

Press enter to exit

And after a few more tests it seems to land on about 700ms \o/ so a 42% performance increase on my dual core cpu. cool! I thought id try a final check aswell, and cranked it up to calculate from the range of 1 million numbers instead of a hundred thousand so i get some time to check the cpu usage, and it looks like this when running without AsParallell:

SingleThread

And with AsParallell:

MultiThread

 

So indeed its using upp both cores now after i helped it a bit \o/. Also you can control it a bit more by specifying .WithDegreeOfParallelism(xxx) where xxx is “the maximum number of concurrently executing tasks that will be used to process the query” (from the intellisense =). That can be handy when for ex downloading stuff from the internet. More than one thread could be handy, but spinning up hundreds of threads probably wont increase the speed alot and will most likely hog up all your bandwidth.

Luca Bolognese talks about this in his awesome session Future Directions for C# and Visual Basicaswell, so check that out for a bit more info. He also shows a a new way of handeling async operations that might be added in the future (after .net 4).

Tags: , , ,

Development

Developer Lunch: Creating SOLID Code

by Christer 28. November 2009 23:36

My turn to select video for our developer lunch. And ofc i had to pick something about the SOLID principles as im a huge fan of atleast knowing how to keep your code nice and clean (I do a less than good job at practicing it though =) Do as i say, dont do as i do).

If you already are familiar with SOLID these clips wont give you much info and can probably stop reading now. But if you are new to it they give a nice overview of the basics, and what it means in code.

For people new to SOLID each letter stands for a principle. S is the Single responsibility principle, O is the Open/Closed principle, L is the Liskov substitution principle, I is the Interface segregation principle and D is the Dependency inversion principle. Each of the 5 movies will give you info on one of these principles.

Creating SOLID Code: Single Responsibility Principle (SRP)

Creating SOLID Code: Open/Closed Principle (OCP)

Creating SOLID Code: Liskov Substitution Principle

Creating SOLID Code: Interface Segregation Principle

Creating SOLID Code: Dependency Inversion Principle

Extra: This movie wasnt planned to be showed during the lunch, but its kinda nice aswell so i added it. They use the project created in the 5 first movies and show how easy adding dependency injection becomes if you are using these principles.

Creating SOLID Code: Refactoring the SOLID episode on DI to use StructureMap

Tags: , ,

Development

Mvc ninjatips

by Christer 28. November 2009 22:41

I was lucky enough to get to check out Scott Hanselman's Pdc session "ASP.NET MVC 2: Ninjas Still on Fire Black Belt Tips" and got really impressed with a few of the features he mentioned.

First thing that hit me was DataAnnotations. I had seen it earlier but i wasnt that impressed as it looked like an easy way to do general validation on serverside, but i couldnt see any good use in the real world. But i changed my mind asap after this session =). If you havent seen DataAnnotations at work before i suggest you check out Johan Driessens excellent post about it at: Testing DataAnnotation-based validation in ASP.NET MVC

So, the "flaws" i noticed the first time i read about DataAnnotations where that it works nicely for code i write myself. But how about generated code? i dont want to modify generated code as my modifications will be removed when i regenerate it. Or if i dont have the code? it cant be used at all then. And lastly, if i dont want to mess up my nice clean code with a bunch of attributes used for validation..
The solution: Buddy classes. By using the attribute MetaDataTypeyou can specify another class that have all the metadata for your object. Since its in another class now it doesnt pollute your code anymore, and it maps them by name, so you can map them to stuff you know will exist in the future.
Also the annotations are extendable so you can write your own validators and they can be generated to clientscript if you want to use that (or write your own).

Another cool feature mentioned in that session was the DisplayForModel/EditorForModel-helpers that use templates to render your stuff.
An empty call to Html.DisplayForModel()/Html.EditorForModel() will use the modelname to look for a template. So it will try and load an ascx-file named <modelname>.ascx and use it to render \o/. You can also specify a name to load a named template.
And for properties there is an attribute you can use (UIHint) to specify a template for them aswell.

The coolest stuff of all is that since it tries to load a template for types you can use it on all existing types aswell! So by creating for ex a DateTime.ascx template you can specify how all rendering of a DateTime will be done.

As a sidenote it also supports fallback. (not mentioned in that session) so if you have an Employee that inherits Person, it will use Person.ascx if it cant find the Employee.ascx template. Or if you have a string it will fallback to object.ascx if it cant find your string.ascx! \o/

So all in all a nice bunch of simple tips that help keep your code clean and help you avoid repeating yourself, and im a big fan of both =).

Other stuff he mentioned was Customizing WebFormViewEngine to select templates depending on custom parameters. Using MvcTurbine to hook up IoC containers. That you can use <%: Model.Prop %> instead of <%= Html.Encode(Model.Prop) %> for automatic HtmlEncoding \o/. And some cool info on customizing the templates used to generate the default code (T4 templates).

If any of the above sounds interesting i suggest you take a look et the complete session available here http://microsoftpdc.com/Sessions/FT59Its about an hour and worth every minute spent watching it.

Tags: , , ,

Development

PDC09 Keynote

by Christer 17. November 2009 18:06

 

Cool keynote so far. Matt Mullenweg (Founder of wordpress) showing of an azure hosted wordpress blog scaling it from one instance to 100 with by only changing one number and a click of a button. cool =) Also Mr icanhascheezburger himself was here and showed their latest site (http://www.oddlyspecific.com/) Also hosted on an azure wordpress blog. 

Getting info about project "Dallas" (http://pinpoint.microsoft.com/en-US/Dallas) atm so will post more info about that when i have it.

 

Tags: , ,

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.


Welcome to the Dropit blog!

Here we, the people that work at Dropit, will write about stuff that interests us. For example web development, especially with .NET and EPiServer - but we'll also talk about other techniques that interest us, marketing on the web, social phenomenons, pop culture, games and software development in general.