2015年8月12日 星期三

[C#] Stopwatch Extensions


Extensions

/// <summary>
/// Stopwatch Extensions
/// </summary>
    public static class StopwatchExtensions
    {
        /// <summary>
        /// Action with Stopwatch
        /// </summary>
        /// <param name="stopwatch">Self</param>
        /// <param name="action">Action</param>
        /// <returns>Stopwatch</returns>
        public static Stopwatch Time(this Stopwatch stopwatch, Action action)
        {
            stopwatch.Reset();
            stopwatch.Start();

            action();

            stopwatch.Stop();
            return stopwatch;
        }

        public static String GetFormatedElapsedTime(this Stopwatch stopwatch)
        {
            // Get the elapsed time as a TimeSpan value.
            TimeSpan ts = stopwatch.Elapsed;

            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            return elapsedTime;
        }
    }

How to use

var sw = new Stopwatch();

Action myAction = () =>
{
    for (int i = 0; i < 5; i++)
    {
        Thread.Sleep(1000);
    }
};

sw.Time(myAction);
Trace.WriteLine(sw.GetFormatedElapsedTime(), "測試時間");
sw = null;


Reference


沒有留言:

張貼留言