老方法,想要全面了解和学习一个类必先看文档 微软文档
1.StopWatch
提供一组方法和属性,可用来测量运行时间。
1.1 属性和方法
属性:
方法:
1.2 使用
csharp
using System.Diagnostics;
namespace Study04_反射专题
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
// 提供一组方法和属性,可用于准确地测量运行时间。
Stopwatch stopwatch = new Stopwatch();
stopwatch.Restart();
Thread.Sleep(1000); // 模拟耗时操作
Console.WriteLine(stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Computer computer = new Computer();
MeasureTimeHelper.Measure(null, () => computer.Add(1, 10000000), out long time);
Console.WriteLine(string.Format("使用{0}ms",time));
Console.ReadKey();
}
}
public class Computer
{
public void Add(int a, int b)
{
int sum = 0;
for (int i = a; i < b; i++)
{
sum += a;
}
Console.WriteLine(sum);
}
}
public static class MeasureTimeHelper
{
public static void Measure(this object obj, Action action, out long time)
{
time = 0;
try
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Restart();
action?.Invoke();
stopwatch.Stop();
time = stopwatch.ElapsedMilliseconds;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}