August 16, 2005

Managed Code Performance

Today I read a very good article from a guy who works for Microsoft BCL Performance section. I found some good interesting concepts. If your interested about code performance you should read this article.

http://blogs.msdn.com/ricom/

I wrote a very simple performance test for testing the for vs foreach & string vs stringbuilder ..etc..etc.. you can find the code below.

Timer class: This calculates the code execution time.

///

/// To get the elapsed the time

///

public class MyTimer

{

long _start;

long _end ;

long _exeTime ;

public string ElapsedTime

{

get

{

//returns the Elapsed time

_exeTime = _end - _start;

return _exeTime.ToString();

}

}

///

/// Start the timer

///

public void Start()

{

_start = DateTime.Now.Ticks ;

}

///

/// End the timer

///

public void Stop()

{

_end= DateTime.Now.Ticks ;

}

}


Some of my test samples


static void Main(string[] args)

{

MyTimer m = new MyTimer();

ArrayList a = new ArrayList();

//For Tests

m.Start();

for(int i=0; i<1000;>

{

string sss= "as" + i.ToString();

Console.WriteLine(sss);

a.Add(sss);

}

m.Stop();

Console.WriteLine(m.ElapsedTime);


m.Start();

for(int i=0; i

{

Console.WriteLine(a[i].ToString());

}

m.Stop();

Console.WriteLine(m.ElapsedTime);

//Foreach Tests

m.Start();

foreach(string s in a)

{

Console.WriteLine(s);

}

m.Stop();

Console.WriteLine(m.ElapsedTime);

//String BuilderTest

StringBuilder name = new StringBuilder();

m.Start();

for(int i=0;i<100000;>

{

name.Append(i.ToString());

}

m.Stop();

Console.WriteLine(name.ToString());

Console.WriteLine(m.ElapsedTime);

}

5 comments:

Anonymous said...

Can I use the same logic to calculate the execution time of a stored procedure I write in SQL Server?

Anonymous said...

Yo Luddy... Where's my answer???

Ludmal de silva said...

ohh sorry dude.. as u knw that im really busy doing BI stuff :-).. u can only check the code execution time. not the SQL server SP execution time. this is only for the code buddy.. time which the compiler takes to compile.

Anonymous said...

What about in SQL Server 2005 then? With all this CLR integration and all... Do you think that it can be used here...

Ludmal de silva said...

sorry 4 late reply gogula. with sql 2005 u can write code behind stored procedures.. u can check the store proc executing time. Its CLR intergrated. for better info u should read this article its really good buddhy.. cheers,
http://msdn.microsoft.com/data/default.aspx?pull=/library/en-us/dnsql90/html/sqlclrguidance.asp