1. 使用 Stopwatch 类
Stopwatch 类是 System.Diagnostics 命名空间中的一个高精度计时器,非常适合用于测量代码块的执行时间。
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Stopwatch stopwatch = new Stopwatch();
// 开始计时
stopwatch.Start();
// 要测量的代码块
DoWork();
// 停止计时
stopwatch.Stop();
// 输出运行时间
Console.WriteLine($"运行时间: {stopwatch.ElapsedMilliseconds} 毫秒");
}
static void DoWork()
{
// 模拟一些工作
System.Threading.Thread.Sleep(1000); // 例如,睡眠1秒
}
}
2. 使用 DateTime 类
虽然 DateTime 类不如 Stopwatch 精确,但在某些简单场景下也可以使用。
using System;
class Program
{
static void Main()
{
DateTime startTime = DateTime.Now;
// 要测量的代码块
DoWork();
DateTime endTime = DateTime.Now;
// 输出运行时间
TimeSpan elapsed = endTime - startTime;
Console.WriteLine($"运行时间: {elapsed.TotalMilliseconds} 毫秒");
}
static void DoWork()
{
// 模拟一些工作
System.Threading.Thread.Sleep(1000); // 例如,睡眠1秒
}
}
3. 使用 BenchmarkDotNet 库
对于更高级和详细的性能测试,可以使用 BenchmarkDotNet 库。它是一个功能强大的基准测试框架,能够生成详细的性能报告。
首先,需要安装 BenchmarkDotNet:
dotnet add package BenchmarkDotNet
然后,可以编写基准测试代码:
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Threading;
public class MyBenchmark
{
[Benchmark]
public void DoWork()
{
Thread.Sleep(1000); // 例如,睡眠1秒
}
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<MyBenchmark>();
}
}
4. 使用 TimeSpan 和 Task
如果你使用的是异步编程模型,可以通过测量 Task 的执行时间来获取运行时间。
using System;
using System.Diagnostics;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
await DoWorkAsync();
stopwatch.Stop();
Console.WriteLine($"运行时间: {stopwatch.ElapsedMilliseconds} 毫秒");
}
static async Task DoWorkAsync()
{
await Task.Delay(1000); // 例如,延迟1秒
}
}
318

被折叠的 条评论
为什么被折叠?



