2023-10-28 03:31:09 +08:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Diagnostics;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace CodeWalker.Core.Utils
|
|
|
|
|
{
|
|
|
|
|
public class DisposableTimer : IDisposable
|
|
|
|
|
{
|
|
|
|
|
public static event Action<TimeSpan, string> TimerStopped;
|
2024-01-07 02:41:10 +08:00
|
|
|
|
public Stopwatch Stopwatch { get; init; }
|
2023-10-28 03:31:09 +08:00
|
|
|
|
|
|
|
|
|
static DisposableTimer()
|
|
|
|
|
{
|
|
|
|
|
#if DEBUG
|
|
|
|
|
TimerStopped += (timeSpan, name) => Debug.WriteLine($"{name} took {timeSpan.TotalMilliseconds} ms");
|
|
|
|
|
#endif
|
|
|
|
|
TimerStopped += (timeSpan, name) => Console.WriteLine($"{name} took {timeSpan.TotalMilliseconds} ms");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string Name { get; private set; }
|
|
|
|
|
|
|
|
|
|
public DisposableTimer(string name)
|
|
|
|
|
{
|
2024-01-07 02:41:10 +08:00
|
|
|
|
Stopwatch = Stopwatch.StartNew();
|
2023-10-28 03:31:09 +08:00
|
|
|
|
Name = name;
|
|
|
|
|
}
|
2024-01-07 02:41:10 +08:00
|
|
|
|
public DisposableTimer(string name, bool start)
|
|
|
|
|
{
|
|
|
|
|
Name = name;
|
|
|
|
|
if (start)
|
|
|
|
|
{
|
|
|
|
|
Stopwatch = Stopwatch.StartNew();
|
|
|
|
|
} else
|
|
|
|
|
{
|
|
|
|
|
Stopwatch = new Stopwatch();
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-10-28 03:31:09 +08:00
|
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
2024-01-07 02:41:10 +08:00
|
|
|
|
Stopwatch.Stop();
|
|
|
|
|
TimerStopped?.Invoke(Stopwatch.Elapsed, Name ?? string.Empty);
|
2023-10-28 03:31:09 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|