Visual Studio .NET 2003Windows 2003.NET 1.1Visual Studio 2005Windows 2000Windows XP.NET 2.0中级开发Visual StudioWindows.NETC#
C# 中的高精度秒表
本文介绍了一个用于 C# 的具有微秒精度的秒表类,它提供分段计时和 System.TimeSpan 接口。
引言
本文介绍了 Performance.Stopwatch
类。该类使用 kernel32.dll 的 QueryPerformanceCounter
提供秒表类似的行为。它提供微秒精度的分段时间和经过时间,并为较长的操作提供格式化的 System.TimeSpan
。该类本质上是一个简洁的秒表,用于测量代码的性能。
背景
所以我决定尝试一下 C# 世界,并想亲自看看我的应用程序的性能与我的 C++ 代码相比如何。为了比较“苹果对苹果”,我需要一个高分辨率的“秒表”来计时我的代码。在进行了一些研究后,我看到了一些替代方法,但我决定自己编写一个,以解决其他方法的不足之处。
使用代码
该类提供以下公共方法
方法 | 描述 |
void Start() |
启动秒表。 |
void Stop() |
停止秒表。 |
void Reset() |
重置秒表。 |
TimeSpan GetElapsedTimeSpan() |
以 System.TimeSpan 的形式返回经过的时间。 |
TimeSpan GetSplitTimeSpan() |
以 System.TimeSpan 的形式返回分段时间。 |
double GetElapsedTimeInMicroseconds() |
以微秒为单位返回经过的时间。 |
double GetSplitTimeInMicroseconds() |
以微秒为单位返回分段时间。 |
以下是一个如何使用该类的示例
Performance.Stopwatch sw = new Performance.Stopwatch();
sw.Start();
for(int i=0; i<10; i++)
{
System.Threading.Thread.Sleep(100);
Console.Write("Split time: ");
Console.Write(sw.GetSplitTimeInMicroseconds().ToString());
Console.WriteLine(" microseconds.");
}
sw.Stop();
Console.Write("Total process time: ");
Console.Write(sw.GetElapsedTimeSpan().ToString());
Console.WriteLine(".");
这段代码产生以下输出
Split time: 101403.390654399 microseconds.
Split time: 202629.105095759 microseconds.
Split time: 302948.000374349 microseconds.
Split time: 403266.616287824 microseconds.
Split time: 503606.184584912 microseconds.
Split time: 603955.251295905 microseconds.
Split time: 704231.124346809 microseconds.
Split time: 804552.254546318 microseconds.
Split time: 904863.327601692 microseconds.
Split time: 1005186.13399189 microseconds.
Total process time: 00:00:01.0050000.
关注点
该类相对于其他类的主要优势在于它为用户提供了一个 System.TimeSpan
接口。这使得显示格式化的状态信息或计算操作完成所需的时间变得容易。该类还具有内置校准,因此连续调用 Start()
和 Stop()
应该会导致 0 +/- 0.500 微秒的经过时间。
历史
- 2006年1月17日 - 初始发布。