如何测量函数运行的时间? [英] How do I measure how long a function is running?
本文介绍了如何测量函数运行的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想看看一个函数运行了多长时间.所以我在我的表单上添加了一个计时器对象,然后我得到了这个代码:
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?
推荐答案
为了避免将来出现计时器问题,以下是正确的代码:
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屋!
查看全文