RealtimeClock.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * NatCorder
  3. * Copyright (c) 2020 Yusuf Olokoba.
  4. */
  5. namespace NatSuite.Recorders.Clocks {
  6. using System;
  7. using System.Runtime.CompilerServices;
  8. using Stopwatch = System.Diagnostics.Stopwatch;
  9. /// <summary>
  10. /// Realtime clock for generating timestamps
  11. /// </summary>
  12. public sealed class RealtimeClock : IClock {
  13. #region --Client API--
  14. /// <summary>
  15. /// Current timestamp in nanoseconds.
  16. /// The very first value reported by this property will always be zero.
  17. /// </summary>
  18. public long timestamp {
  19. [MethodImpl(MethodImplOptions.Synchronized)]
  20. get {
  21. var time = stopwatch.Elapsed.Ticks * 100L;
  22. if (!stopwatch.IsRunning)
  23. stopwatch.Start();
  24. return time;
  25. }
  26. }
  27. /// <summary>
  28. /// Is the clock paused?
  29. /// </summary>
  30. public bool paused {
  31. [MethodImpl(MethodImplOptions.Synchronized)] get => !stopwatch.IsRunning;
  32. [MethodImpl(MethodImplOptions.Synchronized)] set => (value ? (Action)stopwatch.Stop : stopwatch.Start)();
  33. }
  34. /// <summary>
  35. /// Create a realtime clock.
  36. /// </summary>
  37. public RealtimeClock () => this.stopwatch = new Stopwatch();
  38. #endregion
  39. private readonly Stopwatch stopwatch;
  40. }
  41. }