Skip to content

Commit

Permalink
feat: Added a measure unit choice for Timer.LogTime()
Browse files Browse the repository at this point in the history
  • Loading branch information
SolidAlloy committed Oct 6, 2020
1 parent 7d7082a commit 7d61f96
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions Runtime/Timer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@
using System.Diagnostics;
using Debug = UnityEngine.Debug;

public enum TimeUnit { Milliseconds, Nanoseconds }

/// <summary>
/// Basic timer that logs execution time of a method or part of the method. It does not warm up the execution and
/// runs the actions only once.
/// </summary>
public static class Timer
{
private const int NanosecondsInAMillisecond = 1000000;

/// <summary>Log time in ms the action took.</summary>
/// <param name="actionName">Name of the action which execution is measured.</param>
/// <param name="timeUnit">The time unit to use (ms, ns, etc.)</param>
/// <param name="action">Action to execute.</param>
/// <example><code>
/// LogTime("Show popup", () =>
Expand All @@ -20,12 +25,24 @@ public static class Timer
/// dropdownWindow.ShowInPopup();
/// });
/// </code></example>
public static void LogTime(string actionName, Action action)
public static void LogTime(string actionName, TimeUnit timeUnit, Action action)
{
var stopWatch = Stopwatch.StartNew();
action();
stopWatch.Stop();
Debug.Log($"{actionName} took {Convert.ToInt32(stopWatch.ElapsedMilliseconds)} ms.");

switch (timeUnit)
{
case TimeUnit.Milliseconds:
Debug.Log($"{actionName} took {Convert.ToInt32(stopWatch.ElapsedMilliseconds)} ms.");
break;
case TimeUnit.Nanoseconds:
Debug.Log($"{actionName} took {Convert.ToInt32(stopWatch.Elapsed.TotalMilliseconds * NanosecondsInAMillisecond)} ns.");
break;
default:
Debug.Log($"{nameof(LogTime)} does not have an implementation of the following time unit yet: {timeUnit}.");
break;
}
}
}
}

0 comments on commit 7d61f96

Please sign in to comment.