Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created December 6, 2011 15:33
Show Gist options
  • Save hanssens/1438595 to your computer and use it in GitHub Desktop.
Save hanssens/1438595 to your computer and use it in GitHub Desktop.
[C#] StopWatch
public enum StopWatchState
{
Started,
Stopped
}
public class StopWatch : IDisposable
{
public TimeSpan Started { get; private set; }
public TimeSpan Stopped { get; private set; }
public StopWatchState State { get; private set; }
private Dictionary<TimeSpan, string> Logs { get; set; }
public StopWatch()
{
Logs = new Dictionary<TimeSpan, string>();
}
public StopWatch(bool manualEnable) : this()
{
if (!manualEnable)
Start();
}
/// <summary>
/// Starts the current process. This is called automatically, if not explicitely used with the constructor overload for StopWatch(true).
/// </summary>
public void Start()
{
State = StopWatchState.Started;
Started = DateTime.Now.TimeOfDay;
}
/// <summary>
/// Stops the current process.
/// </summary>
public void Stop()
{
Stopped = DateTime.Now.TimeOfDay;
State = StopWatchState.Stopped;
}
/// <summary>
/// Returns the elapsed time between Started and Stopped, as TimeStamp.
/// </summary>
/// <returns>Returns a TimeStamp.</returns>
public TimeSpan Duration()
{
// If the current state is still 'Started', the end time has not been determined yet.
// As a consequence, we dynamically calculate the current remainder here.
// This is not as efficient as calling Stop() first, considering it has a little
// overhead.
if (State == StopWatchState.Started)
return DateTime.Now.TimeOfDay.Subtract(Started);
return Stopped.Subtract(Started);
}
/// <summary>
/// Returns the elapsed time between Started and Stopped, as formatted string.
/// </summary>
/// <param name="format">Custom format for the TimeSpan.ToString(), e.g. [-][d.]hh:mm:ss[.fffffff]</param>
/// <returns>Returns a formatted string.</returns>
public string Duration(string format)
{
return Duration().ToString(format);
}
public void Log(string message)
{
Logs.Add(DateTime.Now.TimeOfDay, message);
}
/// <summary>
/// Returns the contents of the log, and cleans it.
/// </summary>
/// <returns></returns>
public string FlushLog()
{
var returnValue = new StringBuilder();
foreach (var log in Logs)
returnValue.Append(String.Format("{0} {1}\r\n", log.Key, log.Value));
Logs.Clear();
return returnValue.ToString();
}
#region IDisposable Members
public void Dispose()
{
Stop();
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment