Skip to content

Instantly share code, notes, and snippets.

@Zagrophyte
Created August 20, 2021 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zagrophyte/3ed7b63fb28f859cde65e13466ca77e3 to your computer and use it in GitHub Desktop.
Save Zagrophyte/3ed7b63fb28f859cde65e13466ca77e3 to your computer and use it in GitHub Desktop.
namespace SafeAlert.Fircosoft.Net.Diagnostics
open System.Collections.Generic
open System.Diagnostics
open System
open System.Text
/// <summary>
/// Allows ad-hoc timing of any delegate method, or more robust parallel timing of multiple named tasks.
/// </summary>
type PerformanceTimer() =
// Dictionary of named watches.
let watches = new Dictionary<string, Stopwatch>();
/// Dictionary of named watches
member x.Watches = watches
/// Starts a timer with a given name
member x.StartTimer(name: string) =
match watches.TryGetValue(name) with
| true, w -> w.Restart()
| _ -> watches.Add(name, Stopwatch.StartNew())
/// Stops a named timer (if one exists) and returns the time elapsed.
member x.StopTimer(name: string) =
match watches.TryGetValue(name) with
| true, w ->
w.Stop()
w.Elapsed
| _ -> TimeSpan.Zero
/// Stops all timers
member x.StopAllTimers() =
for watch in watches do
watch.Value.Stop()
/// Clears all timers from the report
member x.ClearAllTimers() =
watches.Clear()
/// Dumps a report of all timers and their elapsed times.
member x.GetReport(showMilliseconds : bool) =
let sb = new StringBuilder()
watches
|> Seq.iteri (fun i watch ->
match watch.Value.IsRunning, showMilliseconds with
| true, true -> sb.AppendFormat("{0}: {1:0.00}ms (In Progress)", watch.Key, watch.Value.Elapsed.TotalMilliseconds) |> ignore
| true, false -> sb.AppendFormat("{0}: {1} (In Progress)", watch.Value.Elapsed, watch.Key) |> ignore
| false, true -> sb.AppendFormat("{0}: {1:0.00}ms", watch.Key, watch.Value.Elapsed.TotalMilliseconds) |> ignore
| false, false -> sb.AppendFormat("{0}: {1}", watch.Value.Elapsed, watch.Key) |> ignore
if (not <| (i = watches.Count - 1))
then sb.Append("\r\n") |> ignore )
sb.ToString()
/// Executes the given delegate and returns the elapsed time
member x.TimedAction(action : Action) =
let sw = Stopwatch.StartNew()
action.Invoke()
sw.Stop()
sw.Elapsed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment