計算程式碼片段啟動並執行時間長度,用Stopwatch類
1Stopwatch sw = new Stopwatch();
2sw.Start();
3Thread.Sleep(3000);
4sw.Stop();
5Console.WriteLine(sw.ElapsedMilliseconds());
每次擷取時間都要寫這麼幾行,為此封裝一個計算時間的類
Code
public class RunningTimer : IDisposable
{
private long m_startTimeStamp = 0L;
private long m_endTimeStamp = 0L;
private string m_Desc;
public string Description
{
get { return m_Desc; }
}
public RunningTimer(string description)
{
this.m_Desc = description;
this.m_startTimeStamp = Stopwatch.GetTimestamp();
}
#region IDisposable 成員
public void Dispose()
{
this.m_endTimeStamp = Stopwatch.GetTimestamp();
double elapseSec = (double)(m_endTimeStamp - m_startTimeStamp) / Stopwatch.Frequency;
string showText = string.Format("{0}->using:{1}s", this.m_Desc, elapseSec.ToString("0.00"));
Console.WriteLine(showText);
}
#endregion
}
調用的時候:
1using (RunningTimer timer = new RunningTimer("test"))
2{
3 Thread.Sleep(3000);
4}