How do I measure how long a function is running?

To avoid future problems with a timer, here is the right code:

timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 1; //set interval on 1 milliseconds
timer.Enabled = true; //start the timer
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Enabled = false; //stop the timer

private void timer_Tick(object sender, EventArgs e)
{
   counter++;
   btnTabuSearch.Text = counter.ToString();
}

But it’s the wrong aproach. You must use the Stopwatch (System.Diagnostic) class because it’s a High resolution timer and the word Diagnostic says everything.

So try this:

Stopwatch timer = Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

timer.Stop();  
TimeSpan timespan = timer.Elapsed;

btnTabuSearch.Text = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10);

Leave a Comment