我想看看一个函数运行了多长时间。因此,我在表单上添加了一个计时器对象,然后产生了以下代码:
private int counter = 0;
// Inside button click I have:
timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Stop();
和:
private void timer_Tick(object sender, EventArgs e)
{
counter++;
btnTabuSearch.Text = counter.ToString();
}
但这不算什么。为什么?
最佳答案
为避免定时器将来出现问题,以下是正确的代码:
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();
}
但这是错误的方法。您必须使用Stopwatch (System.Diagnostic)类,因为它是高分辨率计时器,而Diagnostic一词可以说明所有问题。
所以试试这个:
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);