Tuesday, June 24, 2008

.NET : Timing averages

Following on from my previous post about TimeSpan, I needed to do some performance testing and calculate the average time each call took.

This was for a Windows Form project.



for (int i = 0; i < iterations; i++)
{

DateTime startTime;
DateTime endTime;

int iterations;
int alteredIterations = 0;

TimeSpan total = new TimeSpan(0);
TimeSpan average = new TimeSpan(0);

alteredIterations = i + 1;

startTime = DateTime.Now;

... some method ...

endTime = DateTime.Now;

TimeSpan duration = endTime - startTime;

txtDuration.Text = duration.ToString();

total = total + duration;

average = TimeSpan.FromMilliseconds(total.TotalMilliseconds / alteredIterations);

txtAverage.Text = average.ToString();

Application.DoEvents();

}



The "Application.DoEvents();" is to allow Windows some time to update the counts on the screen.

Enjoy!

No comments: