Skip to content

Instantly share code, notes, and snippets.

@STOL4S
Created November 7, 2023 21:37
Show Gist options
  • Save STOL4S/d65edb1fe12035dbb5d847314956df5d to your computer and use it in GitHub Desktop.
Save STOL4S/d65edb1fe12035dbb5d847314956df5d to your computer and use it in GitHub Desktop.
Stopwatch class capable of calculating and displaying the elapsed time between the Start() and Stop() functions. This can be added to any project to easily test the speed of different functions against eachother.
using System;
namespace SimpleStopwatch
{
public class Stopwatch
{
private DateTime _Start;
public TimeSpan Time { get { return _Time; } }
private TimeSpan _Time;
public Stopwatch()
{
this._Start = DateTime.Now;
this._Time = TimeSpan.Zero;
}
public void Start()
{
this._Start = DateTime.Now;
}
public void Stop()
{
this._Time = DateTime.Now - _Start;
}
public override string ToString()
{
return _Time != TimeSpan.Zero ? _Time.Hours.ToString("00") + "h:"
+ _Time.Minutes.ToString("00") + "m:" + _Time.Seconds.ToString("00")
+ "s:" + _Time.Milliseconds.ToString("0000") + "ms" : ThrowNullTimeException();
}
public string ToSeconds()
{
return _Time != TimeSpan.Zero ? _Time.TotalSeconds.ToString("#.###") + "s" : ThrowNullTimeException();
}
public string ToMinutes()
{
return _Time != TimeSpan.Zero ? _Time.TotalMinutes.ToString("#.##") + "m" : ThrowNullTimeException();
}
public string GetResultString()
{
return _Time != TimeSpan.Zero ? "Elapsed Time: " + _Time.Minutes.ToString("00") + "m : " + _Time.Seconds.ToString("00") + "s : " + _Time.Milliseconds.ToString("000") + "ms" : ThrowNullTimeException();
}
public void PrintResult()
{
Console.WriteLine(GetResultString());
}
private string ThrowNullTimeException()
{
throw new Exception("Stopwatch was not stopped prior to requesting ToString(). "
+ "TimeSpan is null, please call Stop() before calling ToString().");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment