我想查看一个函数运行了多长时间。所以我在表单上添加了一个计时器对象,并得到了以下代码:
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();
And:
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();
}
但这是错误的做法。您必须使用秒表(系统.诊断) http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx类,因为它是一个高分辨率定时器和这个词诊断说了一切。
所以试试这个:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)