此示例显示了如何Stopwatch用于对代码块进行基准测试。
using System; using System.Diagnostics; public class Benchmark : IDisposable { private Stopwatch sw; public Benchmark() { sw = Stopwatch.StartNew(); } public void Dispose() { sw.Stop(); Console.WriteLine(sw.Elapsed); } } public class Program { public static void Main() { using (var bench = new Benchmark()) { Console.WriteLine("Hello World"); } } }