(42)C#Stopwatch类(计算程序运行时间)
引入命名空间 using System.Diagnostics;
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10000000; i++); sw.Stop(); Console.WriteLine(sw.Elapsed);//显示程序执行的分钟数,执行的时间如果是分钟以上级别的用这个比较合适 Console.WriteLine(sw.ElapsedMilliseconds);//显示程序执行的秒数 Console.ReadKey(); }
记录代码耗时
class Program { static void Main(string[] args) { Console.WriteLine("start..."); TestTime tt = new TestTime(); Thread.Sleep(3000); tt.writeTime(""); Thread.Sleep(5000); tt.writeTime(""); Thread.Sleep(2000); tt.writeTime(""); Console.WriteLine("end..."); } } public class TestTime { Stopwatch sw; string path = @"D:\time.txt"; //统计次数 int count = 0; //上次时间 long lastTime = 0; public TestTime() { sw = new Stopwatch(); if (File.Exists(path)) { File.WriteAllText(path, ""); } else { File.Create(path).Close(); } sw.Start(); } public void writeTime(string str) { count++; File.AppendAllText(path, "第" + count.ToString() + "调用," + "距离上次时间:" + (sw.ElapsedMilliseconds - lastTime) / 1000 + "秒," + str + "\r\n"); lastTime = sw.ElapsedMilliseconds; } }