c#的程序执行时间计算类
public class TimerHelper { Stopwatch sw; TimeUnit _timeUnit; public TimerHelper() { _timeUnit = TimeUnit.Millisecond; sw = new Stopwatch(); sw.Start(); } public TimerHelper(TimeUnit timeUnit) { _timeUnit = timeUnit; sw = new Stopwatch(); sw.Start(); } public string Finish() { sw.Stop(); if (_timeUnit == TimeUnit.Millisecond) return sw.ElapsedMilliseconds.ToString("0.##") + " ms"; else if (_timeUnit == TimeUnit.Second) return sw.Elapsed.TotalSeconds.ToString("0.##") + " s"; else if (_timeUnit == TimeUnit.Minute) return sw.Elapsed.TotalMinutes.ToString("0.##") + " mins"; else if (_timeUnit == TimeUnit.Hour) return sw.Elapsed.TotalHours.ToString("0.##") + " hrs"; else if (_timeUnit == TimeUnit.Day) return sw.Elapsed.TotalDays.ToString("0.##") + " days"; else return "NOT SUPPORTED"; } } //返回时间格式 public enum TimeUnit { Millisecond, Second, Minute, Hour, Day }
TimerHelper timing = new TimerHelper(TimeUnit.Second);
//做什么
var time= timing.Finish();//返回执行时间