1.DateTime类
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp5 { class Program { static void Main(string[] args) { long sum = 0; DateTime beforDT = System.DateTime.Now; for (int i = 0; i < 10000000; i++) { sum += i; } DateTime afterDT = System.DateTime.Now; TimeSpan ts = afterDT.Subtract(beforDT); Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds); Console.ReadLine(); } } }
2.Stopwatch类
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp5 { class Program { static void Main(string[] args) { long sum = 0; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10000000; i++) { sum += i; } sw.Stop(); TimeSpan timeSpan = sw.Elapsed; Console.WriteLine("Stopwatch总共花费{0}ms.", timeSpan.TotalMilliseconds); Console.ReadLine(); } } }