类名:MyStopwatch
功能:输出一段程序的运行耗时。
用法:
using (new MyStopwatch("Save"))
//
MyStopwatch: Save Took 1000 Ms
{
Thread.Sleep( 1000 );
}
{
Thread.Sleep( 1000 );
}
输出:MyStopwatch: Save Took 1000 Ms
类代码:
代码
public
class
MyStopwatch : IDisposable
{
private string _name;
private Stopwatch _sw;
public MyStopwatch( string name)
{
#if DEBUG
_sw = new Stopwatch();
_name = name;
_sw.Start();
#endif
}
void IDisposable.Dispose()
{
#if DEBUG
if (_name == null ) throw new InvalidOperationException( " you didn't specified operation name in the construction\nyou should use it like this: new MyStopwatch(\ " Operation_Name\ " ) " );
_sw.Stop();
Debug.WriteLine( " MyStopwatch: " + _name + " Took " + _sw.ElapsedMilliseconds + " Ms " );
_sw = null ;
_name = null ;
#endif
}
}
{
private string _name;
private Stopwatch _sw;
public MyStopwatch( string name)
{
#if DEBUG
_sw = new Stopwatch();
_name = name;
_sw.Start();
#endif
}
void IDisposable.Dispose()
{
#if DEBUG
if (_name == null ) throw new InvalidOperationException( " you didn't specified operation name in the construction\nyou should use it like this: new MyStopwatch(\ " Operation_Name\ " ) " );
_sw.Stop();
Debug.WriteLine( " MyStopwatch: " + _name + " Took " + _sw.ElapsedMilliseconds + " Ms " );
_sw = null ;
_name = null ;
#endif
}
}