C# 我如何衡量一个函数运行了多长时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10107140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I measure how long a function is running?
提问by sebastian.roibu
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();
And:
和:
private void timer_Tick(object sender, EventArgs e)
{
counter++;
btnTabuSearch.Text = counter.ToString();
}
But this is not counting anything. Why?
但这不算什么。为什么?
采纳答案by Omar
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 timerand the word Diagnosticsays everything.
但这是错误的方法。您必须使用Stopwatch (System.Diagnostic)类,因为它是一个高分辨率计时器,而Diagnostic这个词说明了一切。
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);
回答by Alain
The best way to see how long a bit of code takes to run is to use System.Diagnostics.Stopwatch.
查看运行一段代码需要多长时间的最佳方法是使用System.Diagnostics.Stopwatch.
Here's an example:
下面是一个例子:
using System.Diagnostics;
#if DEBUG
Stopwatch timer = new Stopwatch();
timer.Start();
#endif
//Long running code
#if DEBUG
timer.Stop();
Debug.WriteLine("Time Taken: " + timer.Elapsed.TotalMilliseconds.ToString("#,##0.00 'milliseconds'"));
#endif
I use the #if DEBUGto ensure the stopwatch code doesn't get into the production release, but you could do without it.
我使用#if DEBUG来确保秒表代码不会进入生产版本,但您可以不用它。
回答by Oded
回答by Matt Burland
For timing a function, you should use the Stopwatch Class
对于计时功能,您应该使用秒表类
Also, the reason your timer isn't counting is because you didn't set an interval for it.
此外,您的计时器不计数的原因是您没有为其设置间隔。
回答by Nikhil Agrawal
Use Stopwatchof System.Diagnostics:
使用System.Diagnostics 的秒表:
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
回答by james lewis
You should use the stopwatch class for timing functions.
您应该将秒表类用于计时功能。
Try the following:
请尝试以下操作:
private int counter = 0;
// setup stopwatch and begin timing
var timer = System.Diagnostics.Stopwatch.StartNew();
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
// stop timer and get elapsed time
timer.Stop();
var elapsed = timer.Elapsed;
// display result time
MessageBox.Show(elapsed.ToString("mm':'ss':'fff"));
回答by Philippe
Perhaps, you could write a method like that:
也许,你可以写一个这样的方法:
public static void Time(Action action)
{
Stopwatch st = new Stopwatch();
st.Start();
action();
st.Stop();
Trace.WriteLine("Duration:" + st.Elapsed.ToString("mm\:ss\.ff"));
}
And use it like that:
并像这样使用它:
Time(()=>
{
CallOfTheMethodIWantToMeasure();
});
回答by batmaci
Visual Studio 2015, 2017 Professional and Enterprise has diagnostic tool. If you have a breakpoint at the end of your function, it will display the time and duration under the Eventstab as shown in the image:
Visual Studio2015、2017 Professional 和 Enterprise 具有诊断工具。如果您在函数末尾有一个断点,它将在“事件”选项卡下显示时间和持续时间,如图所示:
You can see the article Diagnostic Tools debugger window in Visual Studio 2015for more details.
您可以查看Visual Studio 2015 中的诊断工具调试器窗口一文了解更多详细信息。
PS; So far only Xamarin forms, cross platform project doesnt support this feature. I wish that Microsoft brings this great feature for xamarin forms projects as well.
PS; 目前只有 Xamarin 表单,跨平台项目不支持此功能。我希望微软也为 xamarin 表单项目带来这个很棒的功能。
回答by Sumit Deshpande
I reviewed and agreed with all suggestions. But wanted to share one generic implementation for execution time logger where we do not want to implement Stopwatch logic multiple times but still wants to measure execution time for multiple methods.
我并同意所有建议。但是想分享一个执行时间记录器的通用实现,我们不想多次实现秒表逻辑,但仍想测量多个方法的执行时间。
The main reason for not to implement logger in generic way is - method execution is in between stopwatch.Start() and stopwatch.Stop() also we may require method result after the execution for further processing.
不以通用方式实现记录器的主要原因是 - 方法执行在 stopwatch.Start() 和 stopwatch.Stop() 之间,我们也可能在执行后需要方法结果以进行进一步处理。
So to tackle this issue I created following sample implementation where Execution time is logged separately without mixing it with actual method flow.
因此,为了解决这个问题,我创建了以下示例实现,其中单独记录执行时间而不将其与实际方法流混合。
public static class Helper
{
public static T Time<T>(Func<T> method, ILogger log)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = method();
stopwatch.Stop();
log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds));
return result;
}
}
public class Arithmatic
{
private ILogger _log;
public Arithmatic(ILogger log)//Inject Dependency
{
_log = log;
}
public void Calculate(int a, int b)
{
try
{
Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging
Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging
}
catch (Exception ex)
{
_log.Error(ex.Message, ex);
}
}
private string AddNumber(int a, int b)
{
return "Sum is:" + (a + b);
}
private string SubtractNumber(int a, int b)
{
return "Subtraction is:" + (a - b);
}
}
public class Log : ILogger
{
public void Info(string message)
{
Console.WriteLine(message);
}
public void Error(string message, Exception ex)
{
Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace);
}
}
public interface ILogger
{
void Info(string message);
void Error(string message, Exception ex);
}
Calling Part:
调用部分:
static void Main()
{
ILogger log = new Log();
Arithmatic obj = new Arithmatic(log);
obj.Calculate(10, 3);
Console.ReadLine();
}
回答by Harshit Gupta
record the time when current step begins to process
记录当前步骤开始处理的时间
DateTime dtStart = DateTime.Now;
//Calculate the total number of milliseconds request took (Timespan = to represent the time interval)-> current - started time stamp ...
//TotalMilliseconds -->Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
// to measure how long a function is running
var result=((TimeSpan)(DateTime.Now - dtStart)).TotalMilliseconds.ToString("#,##0.00") + "ms";


