怎样衡量一个功能正在运行多久? [英] How do I measure how long a function is running?
本文介绍了怎样衡量一个功能正在运行多久?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想看到一个功能正在运行多长时间。所以我说我的窗体上的计时器对象,我来到了这个code:
I want to see how long a function is running. So I added a timer object on my form, and I came out with this code:
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();
}
不过这还不算什么。为什么呢?
But this is not counting anything. Why?
推荐答案
要避免将来的问题,一个计时器,这里是正确的code:
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();
}
但它是错误的形式给出。您必须使用秒表(System.Diagnostic)类,因为它是一个高分辨率定时器和单词的诊断的说的一切。
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.
所以,试试这个:
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);
这篇关于怎样衡量一个功能正在运行多久?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文