1
1
using System ;
2
2
using System . Diagnostics ;
3
3
using System . Runtime . CompilerServices ;
4
+ using System . Runtime . InteropServices ;
4
5
using BitFaster . Caching . Lru ;
5
6
6
7
namespace BitFaster . Caching
@@ -23,7 +24,16 @@ public readonly struct Duration
23
24
// this also avoids overflow when multipling long.MaxValue by 1.0
24
25
internal static readonly TimeSpan MaxRepresentable = TimeSpan . FromTicks ( ( long ) ( long . MaxValue / 100.0d ) ) ;
25
26
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
27
37
28
38
internal Duration ( long raw )
29
39
{
@@ -33,21 +43,49 @@ internal Duration(long raw)
33
43
/// <summary>
34
44
/// Gets the time since the system epoch.
35
45
/// </summary>
36
- /// <returns>A duration</returns>
46
+ /// <returns>A duration. </returns>
37
47
[ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
38
48
public static Duration SinceEpoch ( )
39
49
{
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
+
40
63
return new Duration ( Stopwatch . GetTimestamp ( ) ) ;
64
+ #endif
41
65
}
42
66
43
67
/// <summary>
44
68
/// Converts the duration to a TimeSpan.
45
69
/// </summary>
46
- /// <returns></returns>
70
+ /// <returns>A TimeSpan. </returns>
47
71
[ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
48
72
public TimeSpan ToTimeSpan ( )
49
73
{
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
+
50
87
return StopwatchTickConverter . FromTicks ( raw ) ;
88
+ #endif
51
89
}
52
90
53
91
/// <summary>
@@ -58,7 +96,21 @@ public TimeSpan ToTimeSpan()
58
96
[ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
59
97
public static Duration FromTimeSpan ( TimeSpan timeSpan )
60
98
{
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
+
61
112
return new Duration ( StopwatchTickConverter . ToTicks ( timeSpan ) ) ;
113
+ #endif
62
114
}
63
115
64
116
/// <summary>
0 commit comments