老方法,想要全面了解和學習一個類必先看文檔 微軟文檔
1.StopWatch
提供一組方法和屬性,可用來測量運行時間。
1.1 屬性和方法
屬性:
方法:
1.2 使用
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);}}}
}