ValueStopwatch.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Diagnostics;
  3. namespace Cysharp.Threading.Tasks.Internal
  4. {
  5. internal readonly struct ValueStopwatch
  6. {
  7. static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
  8. readonly long startTimestamp;
  9. public static ValueStopwatch StartNew() => new ValueStopwatch(Stopwatch.GetTimestamp());
  10. ValueStopwatch(long startTimestamp)
  11. {
  12. this.startTimestamp = startTimestamp;
  13. }
  14. public TimeSpan Elapsed => TimeSpan.FromTicks(this.ElapsedTicks);
  15. public bool IsInvalid => startTimestamp == 0;
  16. public long ElapsedTicks
  17. {
  18. get
  19. {
  20. if (startTimestamp == 0)
  21. {
  22. throw new InvalidOperationException("Detected invalid initialization(use 'default'), only to create from StartNew().");
  23. }
  24. var delta = Stopwatch.GetTimestamp() - startTimestamp;
  25. return (long)(delta * TimestampToTicks);
  26. }
  27. }
  28. }
  29. }