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)
|
2023-06-07 06:30:10 +00:00
|
|
|
|
{
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2023-09-26 13:17:35 +00:00
|
|
|
|
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);
|
|
|
|
|
}
|
2023-09-26 13:17:35 +00:00
|
|
|
|
|
|
|
|
|
return duration;
|
2023-04-25 09:31:15 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|