Stopwatch
就是为此目的而设计的,它是在 .NET 中测量时间执行的最佳方法之一。
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTime 测量 .NET 中的时间执行。
更新:
正如@series0ne 在评论部分指出的那样:如果您想要对某些代码的执行进行真正精确的测量,您将不得不使用操作系统中内置的性能计数器。 following answer 包含一个很好的概述。
根据个人经验,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 是一种商业产品,但会产生非常准确的结果。 - Boost the performance of your applications with .NET profiling
这是一篇关于分析的 StackOverflow 文章:- What Are Some Good .NET Profilers?
我还写了一篇关于使用秒表进行性能分析的文章,您可能想看看 - Performance profiling in .NET
StopWatch
类寻找您的最佳解决方案。
Stopwatch sw = Stopwatch.StartNew();
DoSomeWork();
sw.Stop();
Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);
它还有一个名为 Stopwatch.IsHighResolution
的静态字段。当然,这是硬件和操作系统的问题。
指示计时器是否基于高分辨率性能计数器。
如果您有兴趣了解性能,最好的答案是使用分析器。
否则,System.Diagnostics.StopWatch 提供高分辨率计时器。
在此 Microsoft Doc 之后:
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);
}
}
输出:RunTime 00:00:09.94
StopWatch 将使用高分辨率计数器
秒表通过计算底层计时器机制中的计时器滴答来测量经过的时间。如果安装的硬件和操作系统支持高分辨率性能计数器,则 Stopwatch 类使用该计数器来测量经过的时间。否则, Stopwatch 类使用系统计时器来测量经过的时间。使用频率和 IsHighResolution 字段来确定秒表计时实现的精度和分辨率。
如果您正在测量 IO,那么您的数据可能会受到外部事件的影响,我会非常担心。准确性(正如您在上面指出的那样)。相反,我会进行一系列测量并考虑这些数字的平均值和分布。
您还可以使用“获取自系统启动以来经过的毫秒数”。
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));
}
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);
}
}
不定期副业成功案例分享
ThreadPool.QueueUserWorkItem(delegate { CopyFiles(folder, dest); });
的 foreach 循环,但秒表在一切完成之前停止。