Created
December 26, 2023 15:17
-
-
Save ashalkhakov/d77092b342f28b6a9cf4ae39dc212e4e to your computer and use it in GitHub Desktop.
Hybrid Logical Clock in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace HLC; | |
/// <summary> | |
/// The Hybrid Logical Clock. Contains both Physical Time and Logical Clock inside. | |
/// Grows monotonically, can be used to obtain unique timestamps even if called more often than | |
/// allowed by the physical clock precision. | |
/// | |
/// <see cref="https://cse.buffalo.edu/tech-reports/2014-04.pdf"/> | |
/// </summary> | |
/// <remarks>Single-threaded use only!</remarks> | |
public struct HybridLogicalClock | |
{ | |
private const ulong BitMask = 0xFFL; | |
public HybridLogicalClock() | |
{ | |
_l = 0; | |
_c = 0; | |
} | |
public ulong GetTimeStamp() | |
{ | |
var l1 = _l; | |
// clear out the last 16 bits off of physical timestamp | |
var pt = (ulong)DateTime.Now.Ticks & ~BitMask; | |
_l = Math.Max(l1, pt); | |
if (_l == l1) | |
{ | |
_c++; | |
} | |
else | |
{ | |
_c = 0; | |
} | |
return _l | _c; | |
} | |
private ulong _l; | |
private ushort _c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment