11using System ;
22using System . Diagnostics ;
33using System . Runtime . CompilerServices ;
4+ using System . Runtime . InteropServices ;
45using BitFaster . Caching . Lru ;
56
67namespace BitFaster . Caching
@@ -23,7 +24,16 @@ public readonly struct Duration
2324 // this also avoids overflow when multipling long.MaxValue by 1.0
2425 internal static readonly TimeSpan MaxRepresentable = TimeSpan . FromTicks ( ( long ) ( long . MaxValue / 100.0d ) ) ;
2526
26- internal static readonly Duration Zero = new Duration ( 0 ) ;
27+ internal static readonly Duration Zero = new ( 0 ) ;
28+
29+ #if NET
30+ private static readonly bool IsMacOS = RuntimeInformation . IsOSPlatform ( OSPlatform . OSX ) ;
31+ #else
32+ private static readonly bool IsWindows = RuntimeInformation . IsOSPlatform ( OSPlatform . Windows ) ;
33+
34+ [ DllImport ( "kernel32" ) ]
35+ private static extern long GetTickCount64 ( ) ;
36+ #endif
2737
2838 internal Duration ( long raw )
2939 {
@@ -33,21 +43,49 @@ internal Duration(long raw)
3343 /// <summary>
3444 /// Gets the time since the system epoch.
3545 /// </summary>
36- /// <returns>A duration</returns>
46+ /// <returns>A duration. </returns>
3747 [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
3848 public static Duration SinceEpoch ( )
3949 {
50+ #if NET
51+ if ( IsMacOS )
52+ {
53+ return new Duration ( Stopwatch . GetTimestamp ( ) ) ;
54+ }
55+
56+ return new Duration ( Environment . TickCount64 ) ;
57+ #else
58+ if ( IsWindows )
59+ {
60+ return new Duration ( GetTickCount64 ( ) ) ;
61+ }
62+
4063 return new Duration ( Stopwatch . GetTimestamp ( ) ) ;
64+ #endif
4165 }
4266
4367 /// <summary>
4468 /// Converts the duration to a TimeSpan.
4569 /// </summary>
46- /// <returns></returns>
70+ /// <returns>A TimeSpan. </returns>
4771 [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
4872 public TimeSpan ToTimeSpan ( )
4973 {
74+ #if NET
75+ if ( IsMacOS )
76+ {
77+ return StopwatchTickConverter . FromTicks ( raw ) ;
78+ }
79+
80+ return TimeSpan . FromMilliseconds ( raw ) ;
81+ #else
82+ if ( IsWindows )
83+ {
84+ return TimeSpan . FromMilliseconds ( raw ) ;
85+ }
86+
5087 return StopwatchTickConverter . FromTicks ( raw ) ;
88+ #endif
5189 }
5290
5391 /// <summary>
@@ -58,7 +96,21 @@ public TimeSpan ToTimeSpan()
5896 [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
5997 public static Duration FromTimeSpan ( TimeSpan timeSpan )
6098 {
99+ #if NET
100+ if ( IsMacOS )
101+ {
102+ return new Duration ( StopwatchTickConverter . ToTicks ( timeSpan ) ) ;
103+ }
104+
105+ return new Duration ( ( long ) timeSpan . TotalMilliseconds ) ;
106+ #else
107+ if ( IsWindows )
108+ {
109+ return new Duration ( ( long ) timeSpan . TotalMilliseconds ) ;
110+ }
111+
61112 return new Duration ( StopwatchTickConverter . ToTicks ( timeSpan ) ) ;
113+ #endif
62114 }
63115
64116 /// <summary>
0 commit comments