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

时间:2012-03-31 09:11:59

标签: c#

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

6 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:2)

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

DateTime then = DateTime.Now;

// Your code here

DateTime now = DateTime.Now;

Console.WriteLine(now.Millisecond - then.Millisecond);

答案 2 :(得分:1)

使用Benchmarking Made Easy库

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

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

答案 3 :(得分:0)

编写一个静态类并在静态方法中编写上面的代码...调用该方法在哪里 你想要使用计时器

答案 4 :(得分:0)

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

答案 5 :(得分:-1)

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);

  }

}
相关问题