Skip to content

Instantly share code, notes, and snippets.

@ashalkhakov
Created December 26, 2023 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashalkhakov/d77092b342f28b6a9cf4ae39dc212e4e to your computer and use it in GitHub Desktop.
Save ashalkhakov/d77092b342f28b6a9cf4ae39dc212e4e to your computer and use it in GitHub Desktop.
Hybrid Logical Clock in C#
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