如何计算c#应用程序的执行时间

如何计算c#应用程序的执行时间。 我有c#windows应用程序,我需要计算执行时间,我不知道我必须在哪里继续这个。 谁能帮帮我吗?

使用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); } 

例如,您可以在执行之前和之后使用DateTime.Now ,然后减去毫秒:

 DateTime then = DateTime.Now; // Your code here DateTime now = DateTime.Now; Console.WriteLine(now.Millisecond - then.Millisecond); 

编写一个静态类,并在静态方法中编写上述代码…在您想要使用计时器的地方调用该方法

使用Benchmarking Made Easy库

一种非常简单直接的方法是在C#工具集中使用Jon Skeets Benchmarking Made Easy 。 即使使用StopWatch,您仍然会发现自己在每个要编制基准的位上编写了大量代码。

基准工具集使这一点变得微不足道:你只需将它传递给一个或多个函数并给它们变量输入,它们将一直运行直到完成。 然后可以对每个function的结果进行内省或打印到屏幕上。

您可以使用内置的分析器,它可以在主菜单下的VS2010 Premium和Ultimate中使用 – >分析 – > Profiler

 using system.diagnostic; class Program { static void main(String[] args){ Stopwatch Timer = new Stopwatch(); //here is your code Timer.Stop(); Console.Writeline("Time Taken:" +Timer.Elasped); } }