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

72 lines
1.7 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-09-11 14:57:57 +00:00
public static void 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();
sw.End();
}
2023-09-11 14:57:57 +00:00
public static T Measure<T>(ILog log, string name, Func<T> action, bool debug = false)
{
var sw = Begin(log, name, debug);
var result = action();
sw.End();
return result;
}
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
}
}
}