计算代码段运行的时间长度,用Stopwatch类
1
Stopwatch sw
=
new
Stopwatch();
2 sw.Start();
3 Thread.Sleep( 3000 );
4 sw.Stop();
5 Console.WriteLine(sw.ElapsedMilliseconds());
2 sw.Start();
3 Thread.Sleep( 3000 );
4 sw.Stop();
5 Console.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
}
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
}
调用的时候:
1
using
(RunningTimer timer
=
new
RunningTimer(
"
test
"
))
2 {
3 Thread.Sleep(3000);
4}
2 {
3 Thread.Sleep(3000);
4}