/
Monotonic.cs
49 lines (40 loc) · 1.54 KB
/
Monotonic.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Diagnostics;
namespace Searcher;
/// <summary>
/// A monotonic clock that returns the current date and time, or miliseconds as a long
/// </summary>
public sealed class Monotonic
{
// record when the instance is constructed
private readonly DateTime start;
// current timezone, for UTC calculations
private readonly TimeSpan zone;
// Stopwatch is a monotonic timer
private readonly Stopwatch watch;
public Monotonic()
{
// record the start time and timezone, and starts the stopwatch
watch = Stopwatch.StartNew();
start = DateTime.Now;
zone = TimeZoneInfo.Local.GetUtcOffset(start);
}
/// <summary>
/// A monotonic clock that returns the current local date and time.
/// </summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public DateTime Now() => start.Add(watch.Elapsed);
/// <summary>
/// A monotonic clock that returns the current UTC date and time.
/// </summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public DateTime NowUTC() => start.Subtract(zone).Add(watch.Elapsed);
/// <summary>
/// Get the number of seconds since initialisation.
/// </summary>
public double Seconds => watch.Elapsed.TotalSeconds;
/// <summary>
/// Monotonic milliseconds - arbitrary start point, but monotonic.
/// </summary>
/// <returns>Long number of milliseconds</returns>
public long Milliseconds => watch.ElapsedMilliseconds;
}