可能的重复: 如何测量一个函数运行了多长时间?

我有一个I/O时间的方法,它将数据从一个位置复制到另一个位置。计算执行时间的最佳和最真实的方法是什么?的线程吗?计时器吗?秒表吗?还有其他解决方案吗?我想要最精确的,尽可能简短的。


当前回答

如果您对了解性能感兴趣,最好的答案是使用分析器。

否则,System.Diagnostics.StopWatch提供了一个高分辨率的计时器。

其他回答

根据个人经验,可以使用System.Diagnostics.Stopwatch类来测量方法的执行时间,但是要注意:它并不完全准确!

考虑下面的例子:

Stopwatch sw;

for(int index = 0; index < 10; index++)
{
    sw = Stopwatch.StartNew();
    DoSomething();
    Console.WriteLine(sw.ElapsedMilliseconds);
}

sw.Stop();

例子的结果

132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms

现在你在想;“为什么第一次需要132毫秒,而其他时间都要少得多?”

答案是Stopwatch不能补偿。net中的“背景噪音”活动,比如JITing。因此,当你第一次运行你的方法时,. net会首先JIT它。这样做所花费的时间被添加到执行的时间中。同样,其他因素也会导致执行时间的变化。

您真正应该寻找的绝对准确性是性能分析!

看看下面这些:

RedGate ANTS Performance Profiler是一个商业产品,但可以产生非常准确的结果。-通过.NET分析提高应用程序的性能

这是一篇关于分析的StackOverflow文章:-哪些是一些好的。net分析器?

我还写了一篇关于使用秒表进行性能分析的文章,你可能想看看- .NET中的性能分析

如果您对了解性能感兴趣,最好的答案是使用分析器。

否则,System.Diagnostics.StopWatch提供了一个高分辨率的计时器。

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

下面是微软文档:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    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);
    }
}

输出: 运行时00:00:09.94

您还可以使用这个,“获取自系统启动以来经过的毫秒数”。

System.Environment.TickCount

例如

static void method1()
{
    for (int i = 1; i <= 100; i++)
    {
        Console.WriteLine("Test1 " + i);
    }
}
static void Main(string[] args)
{
    var startTime = Environment.TickCount;
    method1();
    var endTime = Environment.TickCount;
    Console.WriteLine("RunTime " + (endTime - startTime));
}