cs-codex-dist-tests/Framework/Logging/Stopwatch.cs

84 lines
2.1 KiB
C#
Raw Normal View History

2023-04-25 09:31:15 +00:00
using Utils;
namespace Logging
{
public class Stopwatch
{
private readonly DateTime start = DateTime.UtcNow;
2023-09-11 14:57:57 +00:00
private readonly ILog log;
2023-04-25 09:31:15 +00:00
private readonly string name;
private readonly bool debug;
2023-09-11 14:57:57 +00:00
private Stopwatch(ILog log, string name, bool debug)
2023-04-25 09:31:15 +00:00
{
this.log = log;
this.name = name;
this.debug = debug;
}
2023-12-06 08:59:45 +00:00
public static TimeSpan Measure(ILog log, string name, Action action, bool debug = false)
2023-04-25 09:31:15 +00:00
{
var sw = Begin(log, name, debug);
action();
2023-12-06 08:59:45 +00:00
return sw.End();
2023-04-25 09:31:15 +00:00
}
2023-12-06 08:59:45 +00:00
public static StopwatchResult<T> Measure<T>(ILog log, string name, Func<T> action, bool debug = false)
{
var sw = Begin(log, name, debug);
var result = action();
2023-12-06 08:59:45 +00:00
var duration = sw.End();
return new StopwatchResult<T>(result, duration);
}
2023-09-11 14:57:57 +00:00
public static Stopwatch Begin(ILog log)
2023-04-25 09:31:15 +00:00
{
return Begin(log, "");
}
2023-09-11 14:57:57 +00:00
public static Stopwatch Begin(ILog log, string name)
2023-04-25 09:31:15 +00:00
{
return Begin(log, name, false);
}
2023-09-11 14:57:57 +00:00
public static Stopwatch Begin(ILog log, bool debug)
2023-04-25 09:31:15 +00:00
{
return Begin(log, "", debug);
}
2023-09-11 14:57:57 +00:00
public static Stopwatch Begin(ILog log, string name, bool debug)
2023-04-25 09:31:15 +00:00
{
return new Stopwatch(log, name, debug);
}
public TimeSpan End(string msg = "", int skipFrames = 0)
2023-04-25 09:31:15 +00:00
{
var duration = DateTime.UtcNow - start;
var entry = $"{name} {msg} ({Time.FormatDuration(duration)})";
if (debug)
{
log.Debug(entry, 1 + skipFrames);
}
else
{
log.Log(entry);
}
return duration;
2023-04-25 09:31:15 +00:00
}
}
2023-12-06 08:59:45 +00:00
public class StopwatchResult<T>
{
public StopwatchResult(T value, TimeSpan duration)
{
Value = value;
Duration = duration;
}
public T Value { get; }
public TimeSpan Duration { get; }
}
2023-04-25 09:31:15 +00:00
}